package com.ruoyi.feike.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.activiti.domain.ActWorkflowFormData;
import com.ruoyi.activiti.mapper.ActWorkflowFormDataMapper;
import com.ruoyi.activiti.service.impl.ActTaskServiceImpl;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.BaseException;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.feike.domain.*;
import com.ruoyi.feike.domain.dto.BasicInformationDTO2;
import com.ruoyi.feike.domain.dto.WfsLimitSetUpdto;
import com.ruoyi.feike.mapper.*;
import com.ruoyi.feike.service.*;
import com.ruoyi.system.mapper.SysDictDataMapper;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.activiti.api.process.model.ProcessInstance;
import org.activiti.api.process.model.builders.ProcessPayloadBuilder;
import org.activiti.api.process.runtime.ProcessRuntime;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static com.ruoyi.common.utils.DayUtils.typeSort;

@Service
@Slf4j
public class WfsLimitSetUpServiceImpl implements IWfsLimitSetUpService {

    @Value("${wfs.url}")
    private String wfsUrl;

    @Value("${wfs.url2}")
    private String wfsUrl2;

    @Autowired
    private NewSumKeepMapper newSumKeepMapper;

    @Autowired
    private LimitActiveProposalMapper limitActiveProposalMapper;
    @Autowired
    private AnnualReviewyMapper annualReviewyMapper;
    @Autowired
    private DealercodeContractFilingMapper dealercodeContractFilingMapper;
    @Autowired
    private BasicInformationMapper basicInformationMapper;
    @Autowired
    private TemporaryConditionFollowUpMapper temporaryConditionFollowUpMapper;
    @Autowired
    private ILimitActiveProposalService limitActiveProposalService;
    @Autowired
    private IDepositCalculationService depositCalculationService;
    @Autowired
    private IInsuranceCalculationService insuranceCalculationService;
    @Autowired
    private IInsuranceAddressService insuranceAddressService;
    @Autowired
    private ISelfplanInformationService selfplanInformationService;
    @Autowired
    private IBillingInformationService billingInformationService;
    @Autowired
    private INewSumService newSumService;
    @Autowired
    private IPaidSumService paidSumService;

    @Autowired
    private ProcessRuntime processRuntime;
    @Autowired
    private TaskService taskService;

    @Autowired
    private DealerInformationMapper dealerInformationMapper;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private InstanceIdUtil instanceIdUtil;

    @Autowired
    private NotesMapper notesMapper;

    @Autowired
    private ActTaskServiceImpl actTaskService;

    @Autowired
    private IFileuploadService fileuploadService;

    @Autowired
    private  InsuranceDeclarationInfoService  insuranceDeclarationInfoService;

    @Autowired
    private  IHLimitSetupResultService limitSetupResultService;

    @Autowired
    private IAnnualReviewyService annualReviewyService;

    @Autowired
    private IDealerInformationService dealerInformationService;

    @Autowired
    private IApprovalStatusReportService approvalStatusReportService;

    @Autowired
    private SysDictDataMapper dictDataMapper;

    @Autowired
    private INewSumKeepService newSumKeepService;

    @Autowired
    private  ReportDepositTowMapper reportDepositTowMapper;

    @Autowired
    private ReportInsuranceThreeMapper reportInsuranceMapper;


    @Autowired
    private InsuranceAddressMapper insuranceAddressMapper;

    @Autowired
    private BillingInformationMapper billingInformationMapper;

    @ApiOperation("第9条流程提交新增接口")
    @Transactional
    @Override
    public int insertWfsLimitSetUp(WfsLimitSetUpdto wfsLimitSetUpdto) {
        log.info("流程9申请提交参数:"+wfsLimitSetUpdto);
        if (wfsLimitSetUpdto.getDealerName() != null && wfsLimitSetUpdto.getSectorName() !=null){
            //判断是否有在途的同经销商 同品牌的流程
            int i1 = basicInformationMapper.deleteBasicInformationAnnualDealername2(wfsLimitSetUpdto.getDealerName(),wfsLimitSetUpdto.getSectorName());
            if(i1 > 0 ){
                throw  new BaseException("该经销商有正在进行的 WFS Limit Set-Up 流程，请结束流程后再提交");
            }
            //查询有没有保险信息流程
            int i2 = basicInformationMapper.deleteBasicInformationAnnualDealername3(wfsLimitSetUpdto.getDealerName(),wfsLimitSetUpdto.getSectorName());
            if(i2 > 0 ){
                throw  new BaseException("该经销商有正在进行的 保险信息变更 流程，请结束流程后再提交");
            }
        }

        if(wfsLimitSetUpdto.getInsuranceCalculationList()!=null && wfsLimitSetUpdto.getInsuranceCalculationList().get(0).getPlanMethod().equals("自购") ){
            if(wfsLimitSetUpdto.getNewSumList()!= null && wfsLimitSetUpdto.getNewSumList().size()>0 ){
                for (NewSum newSum : wfsLimitSetUpdto.getNewSumList()) {
                    if(StringUtils.isNotEmpty(newSum.getSum())){
                        if(StringUtils.isEmpty(newSum.getInsuranceNo())){
                            throw  new BaseException("缺失保单号,请补充!");
                        }
                    }
                }
            }
        }
        if(wfsLimitSetUpdto.getLimitActiveProposalList() !=null && wfsLimitSetUpdto.getLimitActiveProposalList().size()>0){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            for (LimitActiveProposal limitActiveProposal : wfsLimitSetUpdto.getLimitActiveProposalList()) {
                if(limitActiveProposal.getProposedEnd()==null){
                    throw  new BaseException("Proposed End时间缺失,请检查表单");
                }
                if(limitActiveProposal.getProposedEnd().getTime()<limitActiveProposal.getProposedStart().getTime()){
                    throw  new BaseException("Proposed End时间必须大于当前时间");
                }
            }
        }

        if(wfsLimitSetUpdto.getDepositCalculationList() !=null && wfsLimitSetUpdto.getDepositCalculationList().size()>0){
            List<DepositCalculation> depositCalculationList = wfsLimitSetUpdto.getDepositCalculationList();
            for (DepositCalculation depositCalculation : depositCalculationList) {
                if(StringUtils.isNotEmpty(depositCalculation.getDealerCode()) &&  StringUtils.isNotEmpty(depositCalculation.getTransferTo()) && StringUtils.isNotEmpty(depositCalculation.getTransfertolimittype()) ){
                    String[] split = depositCalculation.getTransferTo().split("-");
                    String TransferToCode = split[0];
                    String limitType = depositCalculation.getLimitType();
                    String limitTypeNew = depositCalculation.getTransfertolimittype();
                    if(limitTypeNew.equals("NORMAL")){
                        limitTypeNew = "NORMAL/DEMO/TEMP";
                    }
                    if(depositCalculation.getDealerCode().equals(TransferToCode) && limitType.equals(limitTypeNew)){
                        throw  new BaseException("不允许操作相同保证金账户互转,请修改");
                    }
                }
            }
        }
        //String instanceId = IdUtils.get16UUID();
        String currentVal = instanceIdUtil.getRedisInstanceId("WLS");
        String instanceId = instanceIdUtil.getIstanceId("WLS", currentVal);
        Notes notes = new Notes();
        notes.setComments(wfsLimitSetUpdto.getComments());
        notes.setConditionNotes(wfsLimitSetUpdto.getConditionNotes());
        notes.setId(IdUtils.simpleUUID());
        notes.setInstanceId(instanceId);
        notesMapper.insertNotes(notes);
        annualReviewyService.saveDbLog("1","新增流程","COMMENTS",instanceId,null,notes,null);

        String title = "";
        BigDecimal GAP = null;
        BigDecimal TOTAL = null;

        BasicInformation basicInformation1 = new BasicInformation();
        basicInformation1.setId(IdUtils.simpleUUID());
        basicInformation1.setInstanceId(instanceId);
        basicInformation1.setDealerNameCN(wfsLimitSetUpdto.getDealerName());
        if(StringUtils.isNotEmpty(wfsLimitSetUpdto.getSectorName())) {
            basicInformation1.setSector(wfsLimitSetUpdto.getSectorName());
        }else {
            List<LimitActiveProposal> limitActiveProposalList = wfsLimitSetUpdto.getLimitActiveProposalList();
            basicInformation1.setSector(limitActiveProposalList.get(0).getSector());
        }

        basicInformation1.setGroupNameCN(wfsLimitSetUpdto.getGroupNameCn());
        basicInformation1.setGroupNameEN(wfsLimitSetUpdto.getGroupName());
        basicInformationMapper.insertBasicInformation(basicInformation1);

        //新增报表
       /* ApprovalStatusReport approvalStatusReport = new ApprovalStatusReport();
        approvalStatusReport.setInstanceId(instanceId);
        approvalStatusReport.setDealerNameCn(wfsLimitSetUpdto.getDealerName());
        approvalStatusReport.setSector(wfsLimitSetUpdto.getSectorName());
        DealerInformation dealerInformation = new DealerInformation();
        dealerInformation.setDealerName(wfsLimitSetUpdto.getDealerName());
        dealerInformation.setMake(wfsLimitSetUpdto.getSectorName());
        List<DealerInformation> dealerInformations = dealerInformationService.selectDealerInformationList(dealerInformation);
        if(dealerInformations!=null && dealerInformations.size()>0){
            String enName = dealerInformations.get(0).getEnName() == null ? " " : dealerInformations.get(0).getEnName();
            String group = dealerInformations.get(0).getGroupName() == null ? " " : dealerInformations.get(0).getGroupName();
            String code = dealerInformations.get(0).getDealerCode() == null ? " " : dealerInformations.get(0).getDealerCode();
            approvalStatusReport.setDealerNameEn(enName);
            approvalStatusReport.setDealerCode(code);
            approvalStatusReport.setGroup(group);
        }
        approvalStatusReport.setRequirement("WFS Limit Set-Up");
        approvalStatusReport.setSituation("under investigation");
        approvalStatusReportService.insertApprovalStatusReport(approvalStatusReport);*/

        if(wfsLimitSetUpdto.getInsuranceDeclarationInfo() !=null && wfsLimitSetUpdto.getInsuranceDeclarationInfo().size()>0){
            List<InsuranceDeclarationInfo> insuranceDeclarationInfoList = wfsLimitSetUpdto.getInsuranceDeclarationInfo();
            InsuranceDeclarationInfo insuranceDeclarationInfo = insuranceDeclarationInfoList.get(0);
            insuranceDeclarationInfo.setId(IdUtils.simpleUUID());
            insuranceDeclarationInfo.setInstanceId(instanceId);
            insuranceDeclarationInfoService.insertInsuranceDeclarationInfo(insuranceDeclarationInfo);
            annualReviewyService.saveDbLog("1","新增流程","保险信息确认",instanceId,null,insuranceDeclarationInfo,null);

        }

        if (wfsLimitSetUpdto.getTemporaryConditionFollowUpList() != null) {
            for (TemporaryConditionFollowUp temporaryConditionFollowUp : wfsLimitSetUpdto.getTemporaryConditionFollowUpList()) {
                if(temporaryConditionFollowUp.getId() == null){
                    temporaryConditionFollowUp.setId(IdUtils.simpleUUID());
                    temporaryConditionFollowUp.setInstanceId(instanceId);
                    temporaryConditionFollowUpMapper.insertTemporaryConditionFollowUp(temporaryConditionFollowUp);
                    annualReviewyService.saveDbLog("1","新增流程","TEMPORARY CONDITION FOLLOW UP",instanceId,null,temporaryConditionFollowUp,null);
                }else{
                    temporaryConditionFollowUpMapper.updateTemporaryConditionFollowUp(temporaryConditionFollowUp);
                }

            }
        }
        if(wfsLimitSetUpdto.getLimitActiveProposalList() !=null && wfsLimitSetUpdto.getLimitActiveProposalList().size()>0){
            for (LimitActiveProposal limitActiveProposal : wfsLimitSetUpdto.getLimitActiveProposalList()) {
                String amt = limitActiveProposal.getProposalActiveLimit().replace(",", "");
                limitActiveProposal.setProposalActiveLimit(Long.valueOf(amt).toString());
                limitActiveProposal.setProposedStart(new Date());
                limitActiveProposal.setId(IdUtils.simpleUUID());
                limitActiveProposal.setInstanceId(instanceId);
                limitActiveProposalService.insertLimitActiveProposal(limitActiveProposal);
                annualReviewyService.saveDbLog("1","新增流程","LIMIT SET-UP PROPOSAL",instanceId,null,limitActiveProposal,null);

            }
        }
        if(wfsLimitSetUpdto.getDepositCalculationList() !=null && wfsLimitSetUpdto.getDepositCalculationList().size()>0){
            for (DepositCalculation depositCalculation : wfsLimitSetUpdto.getDepositCalculationList()) {
                depositCalculation.setId(IdUtils.simpleUUID());
                depositCalculation.setInstanceId(instanceId);
                depositCalculationService.insertDepositCalculation(depositCalculation);
                annualReviewyService.saveDbLog("1","新增流程","DEPOSIT CALCULATION",instanceId,null,depositCalculation,null);

                if(depositCalculation.getGap() !=null && !("".equals(depositCalculation.getGap()))){
                    if(GAP == null){
                        String amt = depositCalculation.getGap().replace(",", "");
                        GAP = new BigDecimal(amt);
                    }else{
                        if(new BigDecimal(depositCalculation.getGap()).compareTo(GAP)==1){
                            String amt = depositCalculation.getGap().replace(",", "");
                            GAP = new BigDecimal(amt);
                        }
                    }
                }
            }
        }
        if(wfsLimitSetUpdto.getInsuranceCalculationList() !=null && wfsLimitSetUpdto.getInsuranceCalculationList().size()>0){
            for (InsuranceCalculation insuranceCalculation : wfsLimitSetUpdto.getInsuranceCalculationList()) {
                if(insuranceCalculation.getPlanMethod().equals("自购")){
                    insuranceCalculation.setPlanRate("");
                }
                insuranceCalculation.setId(IdUtils.simpleUUID());
                insuranceCalculation.setInstanceId(instanceId);
                insuranceCalculationService.insertInsuranceCalculation(insuranceCalculation);
                annualReviewyService.saveDbLog("1","新增流程","INSURANCE CALCULATION",instanceId,null,insuranceCalculation,null);

                if(insuranceCalculation.getPlanTotal() !=null &&  !("".equals(insuranceCalculation.getPlanTotal()))){
                    if(insuranceCalculation.getPlanTotal().equals("-")){
                        TOTAL = new BigDecimal(100);
                    }else{
                        if(TOTAL == null){
                            TOTAL = new BigDecimal(insuranceCalculation.getPlanTotal());
                        }else{
                            if(new BigDecimal(insuranceCalculation.getPlanTotal()).compareTo(TOTAL)==1){
                                TOTAL = new BigDecimal(insuranceCalculation.getPlanTotal());
                            }
                        }
                    }

                }
            }
        }

        if(wfsLimitSetUpdto.getInsuranceAddressList() !=null && wfsLimitSetUpdto.getInsuranceAddressList().size()>0){
            for (InsuranceAddress insuranceAddress : wfsLimitSetUpdto.getInsuranceAddressList()) {
                insuranceAddress.setId(IdUtils.simpleUUID());
                insuranceAddress.setInstanceId(instanceId);
                insuranceAddressService.insertInsuranceAddress(insuranceAddress);
                annualReviewyService.saveDbLog("1","新增流程","保险申报地址",instanceId,null,insuranceAddress,null);

            }
        }

        if(wfsLimitSetUpdto.getSelfplanInformationList() !=null && wfsLimitSetUpdto.getSelfplanInformationList().size()>0){
            for (SelfplanInformation selfplanInformation : wfsLimitSetUpdto.getSelfplanInformationList()) {
                selfplanInformation.setId(IdUtils.simpleUUID());
                selfplanInformation.setInstanceId(instanceId);
                selfplanInformationService.insertSelfplanInformation(selfplanInformation);

            }
        }


        if(wfsLimitSetUpdto.getNewSumList() !=null && wfsLimitSetUpdto.getNewSumList().size()>0){
            for (NewSum newSum : wfsLimitSetUpdto.getNewSumList()) {
                String replace = newSum.getSum().replace(",", "");
                newSum.setSum(replace);
                newSum.setId(IdUtils.simpleUUID());
                newSum.setInstanceId(instanceId);
                newSumService.insertNewSum(newSum);
                annualReviewyService.saveDbLog("1","新增流程","新额度需要的保险",instanceId,null,newSum,null);

            }
        }

        if(wfsLimitSetUpdto.getInsuranceHistory() !=null && wfsLimitSetUpdto.getInsuranceHistory().size()>0){
            for (NewSumKeep newSumKeep : wfsLimitSetUpdto.getInsuranceHistory()) {
                newSumKeep.setInstanceId(instanceId);
                newSumKeepService.insertInsuranceHistory(newSumKeep);
            }
        }

        if(wfsLimitSetUpdto.getPaidSumList() !=null && wfsLimitSetUpdto.getPaidSumList().size()>0){
            for (PaidSum paidSum : wfsLimitSetUpdto.getPaidSumList()) {
                if(StringUtils.isNotEmpty(paidSum.getSum())){
                    paidSum.setId(IdUtils.simpleUUID());
                    paidSum.setInstanceId(instanceId);
                    paidSumService.insertPaidSum(paidSum);
                    annualReviewyService.saveDbLog("1","新增流程","因保险方案变更需补缴的保费",instanceId,null,paidSum,null);
                }
            }
        }

        if(wfsLimitSetUpdto.getLimitSetupResult() !=null && wfsLimitSetUpdto.getLimitSetupResult().size()>0){
            for (HLimitSetupResult hLimitSetupResult : wfsLimitSetUpdto.getLimitSetupResult()) {
                hLimitSetupResult.setInstanceid(instanceId);
                limitSetupResultService.insertHLimitSetupResult(hLimitSetupResult);
                annualReviewyService.saveDbLog("1","新增流程","LIMIT SET UP RESULT",instanceId,null,hLimitSetupResult,null);
            }
        }


        List<Fileupload> application = wfsLimitSetUpdto.getApplication();
        System.out.println("applications==" + application);
        if (application != null && application.size() > 0) {
            for (Fileupload filesVO : application) {
                Fileupload fileupload = new Fileupload();
                fileupload.setFileName(filesVO.getFileName());
                fileupload.setOriginalFileName(filesVO.getName());
                fileupload.setName(filesVO.getName());
                fileupload.setUrl(filesVO.getUrl());
                fileupload.setId(IdUtils.simpleUUID());
                fileupload.setInstanceId(instanceId);
                fileupload.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                fileupload.setCreateName(SecurityUtils.getNickName());
                fileupload.setCreateTime(new Date());
                fileupload.setType("application");
                fileuploadService.insertFileupload(fileupload);
                annualReviewyService.saveDbLog("1","新增流程","File Upload",instanceId,null,fileupload,null);

            }
        }
        List<Fileupload> information = wfsLimitSetUpdto.getInformation();
        System.out.println("informations==" + information);
        if (information != null && information.size() > 0) {
            for (Fileupload filesVO : information) {
                Fileupload fileupload = new Fileupload();
                fileupload.setFileName(filesVO.getFileName());
                fileupload.setOriginalFileName(filesVO.getName());
                fileupload.setName(filesVO.getName());
                fileupload.setUrl(filesVO.getUrl());
                fileupload.setId(IdUtils.simpleUUID());
                fileupload.setInstanceId(instanceId);
                fileupload.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                fileupload.setCreateName(SecurityUtils.getNickName());
                fileupload.setCreateTime(new Date());
                fileupload.setType("information");
                fileuploadService.insertFileupload(fileupload);
                annualReviewyService.saveDbLog("1","新增流程","File Upload",instanceId,null,fileupload,null);

            }
        }

        List<Fileupload> financials = wfsLimitSetUpdto.getFinancials();
        System.out.println("financialss==" + financials);
        if (financials != null && financials.size() > 0) {
            for (Fileupload filesVO : financials) {
                Fileupload fileupload = new Fileupload();
                fileupload.setFileName(filesVO.getFileName());
                fileupload.setOriginalFileName(filesVO.getName());
                fileupload.setName(filesVO.getName());
                fileupload.setUrl(filesVO.getUrl());
                fileupload.setId(IdUtils.simpleUUID());
                fileupload.setInstanceId(instanceId);
                fileupload.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                fileupload.setCreateName(SecurityUtils.getNickName());
                fileupload.setCreateTime(new Date());
                fileupload.setType("financials");
                fileuploadService.insertFileupload(fileupload);
                annualReviewyService.saveDbLog("1","新增流程","File Upload",instanceId,null,fileupload,null);

            }
        }

        List<Fileupload> guarantee = wfsLimitSetUpdto.getGuarantee();
        System.out.println("guarantees==" + guarantee);
        if (guarantee != null && guarantee.size() > 0) {
            for (Fileupload filesVO : guarantee) {
                Fileupload fileupload = new Fileupload();
                fileupload.setFileName(filesVO.getFileName());
                fileupload.setOriginalFileName(filesVO.getName());
                fileupload.setName(filesVO.getName());
                fileupload.setUrl(filesVO.getUrl());
                fileupload.setId(IdUtils.simpleUUID());
                fileupload.setInstanceId(instanceId);
                fileupload.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                fileupload.setCreateName(SecurityUtils.getNickName());
                fileupload.setCreateTime(new Date());
                fileupload.setType("guarantee");
                fileuploadService.insertFileupload(fileupload);
                annualReviewyService.saveDbLog("1","新增流程","File Upload",instanceId,null,fileupload,null);

            }
        }
        List<Fileupload> corporate = wfsLimitSetUpdto.getCorporate();
        System.out.println("corporates==" + corporate);
        if (corporate != null && corporate.size() > 0) {
            for (Fileupload filesVO : corporate) {
                Fileupload fileupload = new Fileupload();
                fileupload.setFileName(filesVO.getFileName());
                fileupload.setOriginalFileName(filesVO.getName());
                fileupload.setName(filesVO.getName());
                fileupload.setUrl(filesVO.getUrl());
                fileupload.setId(IdUtils.simpleUUID());
                fileupload.setInstanceId(instanceId);
                fileupload.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                fileupload.setCreateName(SecurityUtils.getNickName());
                fileupload.setCreateTime(new Date());
                fileupload.setType("corporate");
                fileuploadService.insertFileupload(fileupload);
                annualReviewyService.saveDbLog("1","新增流程","File Upload",instanceId,null,fileupload,null);

            }
        }

        List<Fileupload> other = wfsLimitSetUpdto.getOther();
        System.out.println("others==" + other);
        if (other != null && other.size() > 0) {
            for (Fileupload filesVO : other) {
                Fileupload fileupload = new Fileupload();
                fileupload.setFileName(filesVO.getFileName());
                fileupload.setOriginalFileName(filesVO.getName());
                fileupload.setName(filesVO.getName());
                fileupload.setUrl(filesVO.getUrl());
                fileupload.setId(IdUtils.simpleUUID());
                fileupload.setInstanceId(instanceId);
                fileupload.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                fileupload.setCreateName(SecurityUtils.getNickName());
                fileupload.setCreateTime(new Date());
                fileupload.setType("other");
                fileuploadService.insertFileupload(fileupload);
                annualReviewyService.saveDbLog("1","新增流程","File Upload",instanceId,null,fileupload,null);

            }
        }

        List<Fileupload> opDocument = wfsLimitSetUpdto.getOpDocument();
        if (opDocument != null && opDocument.size() > 0) {
            for (Fileupload filesVO : opDocument) {
                Fileupload fileupload = new Fileupload();
                fileupload.setFileName(filesVO.getFileName());
                fileupload.setOriginalFileName(filesVO.getName());
                fileupload.setName(filesVO.getName());
                fileupload.setUrl(filesVO.getUrl());
                fileupload.setId(IdUtils.simpleUUID());
                fileupload.setInstanceId(instanceId);
                fileupload.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                fileupload.setCreateName(SecurityUtils.getNickName());
                fileupload.setCreateTime(new Date());
                fileupload.setType("opDocument");
                fileuploadService.insertFileupload(fileupload);
                annualReviewyService.saveDbLog("1","新增流程","File Upload",instanceId,null,fileupload,null);

            }
        }

        if (StringUtils.isNotNull(wfsLimitSetUpdto.getName())) {
            title =  wfsLimitSetUpdto.getName();
        } else {
            title = "WFS Limit Set-Up";
        }
        if(TOTAL.compareTo(new BigDecimal(0)) >0){
            TOTAL  = TOTAL.add(new BigDecimal(1));
        }
        System.out.println("GAP为:"+GAP +"   TOTAL为:"+TOTAL);
        if(GAP ==null ){
            throw  new BaseException("gap值为空");
        }

        Authentication.setAuthenticatedUserId(SecurityUtils.getLoginUser()
                .getUser()
                .getUserId()
                .toString());
        Task task = null;

        if (wfsLimitSetUpdto.getCaoGao() != null && wfsLimitSetUpdto.getCaoGao().equals("1")) {

        } else {
            //流程开始
            ProcessInstance processInstance = null;
            if (StringUtils.isNotNull(wfsLimitSetUpdto.getProcessDefinitionKey())) {
                processInstance = processRuntime.start(ProcessPayloadBuilder
                        .start()
                        .withProcessDefinitionKey(wfsLimitSetUpdto.getProcessDefinitionKey())
                        .withName(title)
                        .withBusinessKey(instanceId)
                        // .withVariable("deptLeader",join)
                        .build());
            } else {
                processInstance = processRuntime.start(ProcessPayloadBuilder
                        .start()
                        .withProcessDefinitionKey("WFSLimitSetUp_1")
                        .withName(title)
                        .withBusinessKey(instanceId)
                        // .withVariable("deptLeader",join)
                        .build());
            }

            task = taskService.createTaskQuery()
                    .processInstanceId(processInstance.getId())
                    .singleResult();



            TaskQuery query = taskService.createTaskQuery().taskCandidateOrAssigned(SecurityUtils.getUsername()).active();
            List<Task> todoList = query.list();//获取申请人的待办任务列表
            for (Task tmp : todoList) {
                if (tmp.getProcessInstanceId().equals(processInstance.getId())) {
                    task = tmp;//获取当前流程实例，当前申请人的待办任务
                    break;
                }
            }
            HashMap<String, Object> variables = new HashMap<String, Object>();

            variables.put("GPA", GAP.longValue());
            variables.put("TOTAL", TOTAL.longValue());
            variables.put("FormProperty_0nfqek9",0);
            taskService.complete(task.getId(), variables);

            //发送邮件
            try {
                org.activiti.engine.runtime.ProcessInstance processInstanceMe = runtimeService.createProcessInstanceQuery()
                        .processInstanceId(task.getProcessInstanceId())
                        .singleResult();
                // 上一个节点的执行完，再次查询，获取下一个节点的任务信息
                List<Task> list = taskService.createTaskQuery()
                        .processInstanceId(processInstanceMe.getProcessInstanceId())
                        .list();
                for (Task task1 : list) {
                    ThreadUtil.execute(new Runnable() {

                        @Override
                        public void run() {
                            actTaskService.sendMail(task1, instanceId,null);
                        }
                    });
                }
            } catch (Exception e) {
                log.error("邮件发送失败，{}",e.getMessage());
            }
        }
        AnnualReviewy annualReviewy = new AnnualReviewy();
        annualReviewy.setId(IdUtils.simpleUUID());
        annualReviewy.setTitle(title);
        annualReviewy.setCreateTime(DateUtils.getNowDate());
        annualReviewy.setInstanceId(instanceId);
        annualReviewy.setState("0");
        if (wfsLimitSetUpdto.getCaoGao() != null && wfsLimitSetUpdto.getCaoGao().equals("1")) {//草稿行为时
            annualReviewy.setState("3");
        }
        if (StringUtils.isNotNull(wfsLimitSetUpdto.getProcessDefinitionKey())) {
            annualReviewy.setType(wfsLimitSetUpdto.getProcessDefinitionKey());
        } else {
            annualReviewy.setType("WFSLimitSetUp_1");
        }
        annualReviewy.setCreateName(SecurityUtils.getNickName());
        annualReviewy.setCreateBy(SecurityUtils.getUsername());
        annualReviewy.setCreateTime(DateUtils.getNowDate());
        annualReviewy.setGAP(GAP.longValue());
        annualReviewy.setTOTAL(TOTAL.longValue());
        if(ObjectUtil.isNotEmpty(task)){
            annualReviewy.setStartNode(task.getName());
        }
        int i = annualReviewyMapper.insertAnnualReviewy(annualReviewy);
        annualReviewyService.saveDbLog("1","新增流程",null ,instanceId,null,annualReviewy,null);

        return i;
    }

    @Override
    public WfsLimitSetUpdto selectWfsLimitSetUpdto(String instanceId) {
        WfsLimitSetUpdto wfsLimitSetUpdto = new WfsLimitSetUpdto();
        AnnualReviewy annualReviewy = annualReviewyMapper.selectAnnualReviewyByInstanceId(instanceId);
        wfsLimitSetUpdto.setAnnualReviewy(annualReviewy);
        List<BasicInformation> basicInformations = basicInformationMapper.selectDealerGroupByByInstanceId(instanceId);
        BasicInformation basicInformation = basicInformations.get(0);
        wfsLimitSetUpdto.setDealerName(basicInformation.getDealerNameCN());
        wfsLimitSetUpdto.setSectorName(basicInformation.getSector());
        wfsLimitSetUpdto.setGroupName(basicInformation.getGroupNameEN());
        wfsLimitSetUpdto.setGroupNameCn(basicInformation.getGroupNameCN());
        List<String> dealernameList = new ArrayList<>();
        dealernameList.add(basicInformations.get(0).getDealerNameCN());
        List<TemporaryConditionFollowUp> temporaryConditionFollowUpList = temporaryConditionFollowUpMapper.selectTemporaryConditionFollowUpByDealername(dealernameList);
        if (temporaryConditionFollowUpList != null && temporaryConditionFollowUpList.size() > 0) {
            wfsLimitSetUpdto.setTemporaryConditionFollowUpList(temporaryConditionFollowUpList);
        }
        LimitActiveProposal limitActiveProposal = new LimitActiveProposal();
        limitActiveProposal.setInstanceId(instanceId);
        List<LimitActiveProposal> limitActiveProposals = limitActiveProposalService.selectLimitActiveProposalList(limitActiveProposal);
        Long currentActiveLimit = null;
        Long currentActiveLimitNORMAL= null;
        if(limitActiveProposals!=null && limitActiveProposals.size()>0){
            for (LimitActiveProposal limitActiveProposal1 : limitActiveProposals) {
                if(limitActiveProposal1.getLimitType().equals("TEMP")){
                    currentActiveLimit = limitActiveProposal1.getCurrentCreditLimit();
                }else if(limitActiveProposal1.getLimitType().equals("NORMAL")){
                    currentActiveLimitNORMAL = limitActiveProposal1.getCurrentCreditLimit();
                }
            }
        }
        if(currentActiveLimit!= null && currentActiveLimitNORMAL!=null ){
            for (LimitActiveProposal limitActiveProposal1 : limitActiveProposals) {
                if(limitActiveProposal1.getLimitType().equals("NORMAL")){
                    limitActiveProposal1.setCurrentCreditLimit2(currentActiveLimit+currentActiveLimitNORMAL);
                }else{
                    limitActiveProposal1.setCurrentCreditLimit2(limitActiveProposal1.getCurrentCreditLimit());
                }
            }
        }else{
            for (LimitActiveProposal limitActiveProposal1 : limitActiveProposals) {
                limitActiveProposal1.setCurrentCreditLimit2(limitActiveProposal1.getCurrentCreditLimit());
            }
        }

        for (LimitActiveProposal who : limitActiveProposals) {
            who.setSort(typeSort(who.getLimitType()));
        }
        limitActiveProposals.sort(Comparator.comparingInt(LimitActiveProposal::getSort));
        HLimitSetupResult hLimitSetupResult = new HLimitSetupResult();
        hLimitSetupResult.setInstanceid(instanceId);
        List<HLimitSetupResult> hLimitSetupResults = limitSetupResultService.selectHLimitSetupResultList(hLimitSetupResult);
        for (HLimitSetupResult limitSetupResult : hLimitSetupResults) {
            limitSetupResult.setSort(typeSort(limitSetupResult.getLimittype()));
        }
        hLimitSetupResults.sort(Comparator.comparingInt(HLimitSetupResult::getSort));
        DepositCalculation depositCalculation = new DepositCalculation();
        depositCalculation.setInstanceId(instanceId);
        List<DepositCalculation> depositCalculations = depositCalculationService.selectDepositCalculationList(depositCalculation);
        int depositFlag = 0;
        for (DepositCalculation calculation : depositCalculations) {
            calculation.setSort(typeSort(calculation.getLimitType()));
            if(calculation.getGap()!=null){
                String amt = calculation.getGap().replace(",", "");
                BigDecimal gap = new BigDecimal(amt);
                if(gap.compareTo(new BigDecimal(0) )<=0){
                    depositFlag =1;
                }else{
                    depositFlag =0;
                }
            }
        }
        wfsLimitSetUpdto.setDepositFlag(depositFlag);
        depositCalculations.sort(Comparator.comparingInt(DepositCalculation::getSort));

        InsuranceCalculation insuranceCalculation = new InsuranceCalculation();
        insuranceCalculation.setInstanceId(instanceId);
        List<InsuranceCalculation> insuranceCalculations = insuranceCalculationService.selectInsuranceCalculationList(insuranceCalculation);
        InsuranceAddress insuranceAddress = new InsuranceAddress();
        insuranceAddress.setInstanceId(instanceId);
        List<InsuranceAddress> insuranceAddresses = insuranceAddressService.selectInsuranceAddressList(insuranceAddress);
        SelfplanInformation selfplanInformation = new SelfplanInformation();
        selfplanInformation.setInstanceId(instanceId);
        List<SelfplanInformation> selfplanInformations = selfplanInformationService.selectSelfplanInformationList(selfplanInformation);
        BillingInformation billingInformation = new BillingInformation();
        billingInformation.setInstanceId(instanceId);
        List<BillingInformation> billingInformations = billingInformationService.selectBillingInformationList(billingInformation);

        List<InsuranceDeclarationInfo> insuranceDeclarationInfoByInstanceId = insuranceDeclarationInfoService.getInsuranceDeclarationInfoByInstanceId(instanceId);
        if(insuranceDeclarationInfoByInstanceId!= null && insuranceDeclarationInfoByInstanceId.size()>0){
            wfsLimitSetUpdto.setInsuranceDeclarationInfo(insuranceDeclarationInfoByInstanceId);
        }
        NewSum newSum = new NewSum();
        newSum.setInstanceId(instanceId);
        List<NewSum> newSumList = newSumService.selectNewSumList(newSum);



        NewSumKeep sumKeep = new NewSumKeep();
        sumKeep.setDealerName(basicInformation.getDealerNameCN());
        sumKeep.setSector(basicInformation.getSector());
        List<NewSumKeep> insuranceHistory = newSumKeepService.selectNewSumKeepList4(sumKeep);

        InsuranceDeclarationInfo insuranceDeclarationInfo = new InsuranceDeclarationInfo();
        insuranceDeclarationInfo.setInstanceId(instanceId);
        List<InsuranceDeclarationInfo> insuranceDeclarationInfos = insuranceDeclarationInfoService.selectDepositDeclarationInfoList(insuranceDeclarationInfo);
        if(insuranceDeclarationInfos !=null && insuranceDeclarationInfos.size()>0){
            wfsLimitSetUpdto.setDepositDeclarationInfo(insuranceDeclarationInfos);
        }else{
            ArrayList<InsuranceDeclarationInfo> infos = new ArrayList<>();
            InsuranceDeclarationInfo insuranceDeclarationInfoTemp = new InsuranceDeclarationInfo();
            insuranceDeclarationInfoTemp.setBankFeedbackNo("");
            insuranceDeclarationInfoTemp.setPremiumReceivedDate(null);
            insuranceDeclarationInfoTemp.setReceivedAmount("");
            insuranceDeclarationInfoTemp.setNote("");
            infos.add(insuranceDeclarationInfoTemp);
            wfsLimitSetUpdto.setDepositDeclarationInfo(infos);
        }

        PaidSum paidSum = new PaidSum();
        paidSum.setInstanceId(instanceId);
        List<PaidSum> paidSums = paidSumService.selectPaidSumList(paidSum);

        Fileupload fileupload = new Fileupload();
        fileupload.setInstanceId(instanceId);
        fileupload.setType("application");
        List<Fileupload> application = fileuploadService.selectFileuploadList(fileupload);
        if (application != null) {
            wfsLimitSetUpdto.setApplication(application);
        }

        fileupload.setType("information");
        List<Fileupload> information = fileuploadService.selectFileuploadList(fileupload);
        if (information != null) {
            wfsLimitSetUpdto.setInformation(information);
        }
        fileupload.setType("financials");
        List<Fileupload> financials = fileuploadService.selectFileuploadList(fileupload);
        if (financials != null) {
            wfsLimitSetUpdto.setFinancials(financials);
        }
        fileupload.setType("guarantee");
        List<Fileupload> guarantee = fileuploadService.selectFileuploadList(fileupload);
        if (guarantee != null) {
            wfsLimitSetUpdto.setGuarantee(guarantee);
        }
        fileupload.setType("corporate");
        List<Fileupload> corporate = fileuploadService.selectFileuploadList(fileupload);
        if (corporate != null) {
            wfsLimitSetUpdto.setCorporate(corporate);
        }
        fileupload.setType("other");
        List<Fileupload> other = fileuploadService.selectFileuploadList(fileupload);
        if (other != null) {
            wfsLimitSetUpdto.setOther(other);
        }
        fileupload.setType("opDocument");
        List<Fileupload> opDocument = fileuploadService.selectFileuploadList(fileupload);
        if (opDocument != null) {
            wfsLimitSetUpdto.setOpDocument(opDocument);
        }
        Notes notes = notesMapper.selectNotesByInstanceId(instanceId);
        wfsLimitSetUpdto.setComments(notes.getComments());
        wfsLimitSetUpdto.setConditionNotes(notes.getConditionNotes());
        wfsLimitSetUpdto.setAnnualReviewy(annualReviewy);
        wfsLimitSetUpdto.setLimitActiveProposalList(limitActiveProposals);
        wfsLimitSetUpdto.setLimitSetupResult(hLimitSetupResults);
        wfsLimitSetUpdto.setDepositCalculationList(depositCalculations);
        wfsLimitSetUpdto.setInsuranceCalculationList(insuranceCalculations);
        wfsLimitSetUpdto.setInsuranceAddressList(insuranceAddresses);
        wfsLimitSetUpdto.setSelfplanInformationList(selfplanInformations);
        wfsLimitSetUpdto.setBillingInformationList(billingInformations);
        wfsLimitSetUpdto.setNewSumList(newSumList);
        wfsLimitSetUpdto.setPaidSumList(paidSums);
        wfsLimitSetUpdto.setInsuranceHistory(insuranceHistory);
        return wfsLimitSetUpdto;
    }

    @ApiOperation("第9条流程提交修改接口")
    @Transactional
    @Override
    public String  updateWfsLimitSetUp(WfsLimitSetUpdto wfsLimitSetUpdto) {
        log.info("流程9修改提交参数:"+wfsLimitSetUpdto);
        AnnualReviewy annualReviewy1 = wfsLimitSetUpdto.getAnnualReviewy();
        if(annualReviewy1!=null){
            wfsLimitSetUpdto.setInstanceId(annualReviewy1.getInstanceId());
        }else{
            String id = wfsLimitSetUpdto.getInstanceId();
            if(StringUtils.isEmpty(id)){
                throw  new BaseException("数据异常，请重新提交");
            }
        }

        if(wfsLimitSetUpdto.getInsuranceCalculationList()!=null && wfsLimitSetUpdto.getInsuranceCalculationList().get(0).getPlanMethod().equals("缴纳保费") && StringUtils.isNotEmpty(wfsLimitSetUpdto.getName()) && wfsLimitSetUpdto.getName().equals("DM")){
            List<BillingInformation> billingInformationList = wfsLimitSetUpdto.getBillingInformationList();
            if(billingInformationList ==null || billingInformationList.size() ==0 || StringUtils.isEmpty(billingInformationList.get(0).getEmailAddress()) ){
                throw  new BaseException("缺失保险经销商基础信息,请在信息维护Dealer Insurance中填写后提交");
            }

        }
        if(wfsLimitSetUpdto.getInsuranceCalculationList()!=null && wfsLimitSetUpdto.getInsuranceCalculationList().get(0).getPlanMethod().equals("自购") ){
            if(wfsLimitSetUpdto.getNewSumList()!= null && wfsLimitSetUpdto.getNewSumList().size()>0 ){
                for (NewSum newSum : wfsLimitSetUpdto.getNewSumList()) {
                    if(StringUtils.isNotEmpty(newSum.getSum())){
                        if(StringUtils.isEmpty(newSum.getInsuranceNo())){
                            throw  new BaseException("缺失保单号,请补充!");
                        }
                    }
                }
            }
        }

        if(wfsLimitSetUpdto.getDepositCalculationList() !=null && wfsLimitSetUpdto.getDepositCalculationList().size()>0){
            List<DepositCalculation> depositCalculationList = wfsLimitSetUpdto.getDepositCalculationList();
            for (DepositCalculation depositCalculation : depositCalculationList) {
                if(StringUtils.isNotEmpty(depositCalculation.getDealerCode()) &&  StringUtils.isNotEmpty(depositCalculation.getTransferTo()) && StringUtils.isNotEmpty(depositCalculation.getTransfertolimittype()) ){
                    String[] split = depositCalculation.getTransferTo().split("-");
                    String TransferToCode = split[0];
                    if(depositCalculation.getDealerCode().equals(TransferToCode) && depositCalculation.getLimitType().equals(depositCalculation.getTransfertolimittype())){
                        throw  new BaseException("不允许操作相同保证金账户互转,请修改");
                    }
                }
            }
        }

        if(wfsLimitSetUpdto.getName() !=null && wfsLimitSetUpdto.getName().equals("DM")){
            //删除历史保险
            NewSum newSum = new NewSum();
            newSum.setInstanceId(wfsLimitSetUpdto.getInstanceId());
            List<NewSum> newSumList = newSumService.selectNewSumList(newSum);
            for (NewSum sum : newSumList) {
                newSumService.deleteNewSumById(sum.getId());
                annualReviewyService.saveDbLog("2","删除表单信息","新额度需要的保险" ,wfsLimitSetUpdto.getInstanceId(),sum,null,null);
            }
            //删除补缴的保费
            PaidSum paidSum = new PaidSum();
            paidSum.setInstanceId(wfsLimitSetUpdto.getInstanceId());
            List<PaidSum> paidSums = paidSumService.selectPaidSumList(paidSum);
            for (PaidSum sum : paidSums) {
                paidSumService.deletePaidSumById(sum.getId());
                annualReviewyService.saveDbLog("2","删除表单信息","因保险方案变更需补缴的保费" ,wfsLimitSetUpdto.getInstanceId(),sum,null,null);

            }
        }
        if (wfsLimitSetUpdto.getCaoGao() != null && (wfsLimitSetUpdto.getCaoGao().equals("0") || wfsLimitSetUpdto.getCaoGao().equals("1"))) {
            //删除历史保险
            NewSum newSum = new NewSum();
            newSum.setInstanceId(wfsLimitSetUpdto.getInstanceId());
            List<NewSum> newSumList = newSumService.selectNewSumList(newSum);
            for (NewSum sum : newSumList) {
                newSumService.deleteNewSumById(sum.getId());
                annualReviewyService.saveDbLog("2","删除表单信息","新额度需要的保险" ,wfsLimitSetUpdto.getInstanceId(),sum,null,null);
            }
            //删除补缴的保费
            PaidSum paidSum = new PaidSum();
            paidSum.setInstanceId(wfsLimitSetUpdto.getInstanceId());
            List<PaidSum> paidSums = paidSumService.selectPaidSumList(paidSum);
            for (PaidSum sum : paidSums) {
                paidSumService.deletePaidSumById(sum.getId());
                annualReviewyService.saveDbLog("2","删除表单信息","因保险方案变更需补缴的保费" ,wfsLimitSetUpdto.getInstanceId(),sum,null,null);

            }
        }

        if(wfsLimitSetUpdto.getIsAdopt()!= null && wfsLimitSetUpdto.getIsAdopt()==1 && wfsLimitSetUpdto.getPaidSumList()!= null && wfsLimitSetUpdto.getPaidSumList().size()>0
        )
        {
            //是否有因费率变更的保险
            List<PaidSum> paidSumList = wfsLimitSetUpdto.getPaidSumList();
            for (PaidSum paidSum : paidSumList) {
                if(paidSum.getDealerId()!=null &&  paidSum.getRate()!=null){
                    NewSumKeep newSumKeep = newSumKeepMapper.selectNewSumKeepById(paidSum.getDealerId());
                    NewSumKeep newSumKeep2 = new NewSumKeep();
                    String rate = paidSum.getRate().replace("%", "");
                    Double newRate = Double.valueOf(rate);
                    BigDecimal bigDecimal = new BigDecimal(newRate);
                    BigDecimal divide = bigDecimal.divide(new BigDecimal(100),7,BigDecimal.ROUND_HALF_UP);
                    String s = Arith.removeZeros(divide.toString());
                    newSumKeep2.setPlanRate(s.toString());
                    newSumKeep2.setId(paidSum.getDealerId());
                    newSumKeep2.setInstanceId(wfsLimitSetUpdto.getInstanceId());
                    newSumKeep2.setOldRate(newSumKeep.getPlanRate());
                    newSumKeep2.setNote("费率变更");
                    NewSumKeep newSumKeep1 = newSumKeepMapper.selectNewSumKeepById(paidSum.getDealerId());
                    newSumKeepMapper.updateNewSumKeep(newSumKeep2);
                    annualReviewyService.saveDbLog("3","修改历史保险信息",null ,wfsLimitSetUpdto.getInstanceId(),newSumKeep1,newSumKeep2,null);


                    //插入报表1和报表3
                    ReportInsurance reportInsurance = new ReportInsurance();
                    reportInsurance.setInstanceId(wfsLimitSetUpdto.getInstanceId());
                    reportInsurance.setDealerName(paidSum.getDealerName());
                    reportInsurance.setSector(paidSum.getSector());
                    reportInsurance.setEffectiveDate(paidSum.getEffectiveDate());
                    reportInsurance.setExpiryDate(paidSum.getExpiryDate());
                    reportInsurance.setCoverage(paidSum.getSum());
                    reportInsurance.setRate(divide.toString());
                    reportInsurance.setPremium(paidSum.getPaidsum());
                    if(newSumKeep!=null && newSumKeep.getPlanRate()!=null){
                        String planRate = newSumKeep.getPlanRate();
                        BigDecimal subtract = new BigDecimal(newSumKeep2.getPlanRate()).subtract(new BigDecimal(planRate));
                        reportInsurance.setRate(subtract.toString());
                        reportInsurance.setNote("费率变更");
                    }

                    ReportInsuranceMapper bean = SpringUtils.getBean(ReportInsuranceMapper.class);
                    bean.insertReportInsurance(reportInsurance);
                    annualReviewyService.saveDbLog("1","新增保险报表记录",null ,wfsLimitSetUpdto.getInstanceId(),null,reportInsurance,null);


                    ReportInsuranceThree reportInsuranceThree = new ReportInsuranceThree();
                    reportInsuranceThree.setDealerName(paidSum.getDealerName());
                    reportInsuranceThree.setSector(paidSum.getSector());
                    reportInsuranceThree.setInstanceId(wfsLimitSetUpdto.getInstanceId());
                    reportInsuranceThree.setPremium(paidSum.getPaidsum());
                    List<InsuranceDeclarationInfo> insuranceDeclarationInfos = wfsLimitSetUpdto.getInsuranceDeclarationInfo();
                    if(CollectionUtil.isNotEmpty(insuranceDeclarationInfos)){
                        reportInsuranceThree.setBankFeedbackNo(insuranceDeclarationInfos.get(0).getBankFeedbackNo());
                        reportInsuranceThree.setPremiumReceivedDate(insuranceDeclarationInfos.get(0).getPremiumReceivedDate());
                        reportInsuranceThree.setReceivedAmount(insuranceDeclarationInfos.get(0).getReceivedAmount());
                        reportInsuranceThree.setNoteOne(insuranceDeclarationInfos.get(0).getNote());
                    }
                    ReportInsuranceThreeMapper bean1 = SpringUtils.getBean(ReportInsuranceThreeMapper.class);
                    bean1.insertReportInsuranceThree(reportInsuranceThree);
                    annualReviewyService.saveDbLog("1","新增保险报表记录",null ,wfsLimitSetUpdto.getInstanceId(),null,reportInsuranceThree,null);
                }
            }
        }
        if(wfsLimitSetUpdto.getIsAdopt()!= null && wfsLimitSetUpdto.getIsAdopt()==1
                && wfsLimitSetUpdto.getNewSumList()!= null && wfsLimitSetUpdto.getNewSumList().size()>0
                && wfsLimitSetUpdto.getInsuranceCalculationList() != null && wfsLimitSetUpdto.getInsuranceCalculationList().size()>0 )
        {

            //保险购买确认report
            List<NewSum> newSums = wfsLimitSetUpdto.getNewSumList();
            //根据id进行分组
            ArrayList<NewSum> newSumsGroup = new ArrayList<>();
            if(newSums !=null && newSums.size()>0){
                Map<String, List<NewSum>> collect = newSums.stream().collect(Collectors.groupingBy(NewSum::getDealerId));
                for (String key : collect.keySet()) {
                    List<NewSum> sums = collect.get(key);
                    if(sums.size()==1){
                        newSumsGroup.add(sums.get(0));
                    }else if (sums.size()>1){
                        boolean flag = false;
                        for (NewSum sum : sums) {
                            if(sum.getSumDay().equals("-")){
                                flag = true;
                                break;
                            }
                        }
                        if(flag){
                            for (NewSum sum : sums) {
                                newSumsGroup.add(sum);
                            }
                        }else{
                            NewSum newSum = sums.stream().min(Comparator.comparing(NewSum::getStartDate)).get();
                            NewSum newSum1 = sums.stream().max(Comparator.comparing(NewSum::getEndDate)).get();
                            BigDecimal  sumAmt = BigDecimal.ZERO;
                            for (NewSum sum : sums) {
                                sumAmt = sumAmt.add(new BigDecimal(sum.getSumDay()));
                            }
                            NewSum newSum2 = new NewSum();
                            newSum2.setSum(sums.get(0).getSum());
                            newSum2.setSumDay(sumAmt.toString());
                            newSum2.setDealerId(sums.get(0).getDealerId());
                            newSum2.setSector(sums.get(0).getSector());
                            newSum2.setDealerName(sums.get(0).getDealerName());
                            newSum2.setStartDate(newSum.getStartDate());
                            newSum2.setEndDate(newSum1.getEndDate());
                            newSumsGroup.add(newSum2);
                        }
                    }
                }
            }
            newSums = newSumsGroup;
            InsuranceCalculation insuranceCalculation = new InsuranceCalculation();
            insuranceCalculation.setInstanceId(wfsLimitSetUpdto.getInstanceId());
            List<InsuranceCalculation> insuranceCalculations = insuranceCalculationService.selectInsuranceCalculationList(insuranceCalculation);
            if(newSums !=null && newSums.size()>0 && insuranceCalculations!=null &&  insuranceCalculations.size()>0){
                for (NewSum sum : newSums) {
                    String replacesum = sum.getSum().replace(",", "");
                    sum.setSum(replacesum);
                    if(sum.getSum() !=null && sum.getSector() !=null && sum.getStartDate() !=null && sum.getEndDate() !=null && insuranceCalculations.get(0).getPlanRate()!=null ){
                        BigDecimal divide = BigDecimal.ZERO;
                        INewSumKeepService newSumKeepService = SpringUtils.getBean(INewSumKeepService.class);
                        NewSumKeep sumKeep = new NewSumKeep();
                        sumKeep.setInstanceId(wfsLimitSetUpdto.getInstanceId());
                        sumKeep.setId(IdUtils.simpleUUID());
                        sumKeep.setDealerName(sum.getDealerName());
                        sumKeep.setSector(sum.getSector());
                        sumKeep.setEffectiveDate(sum.getStartDate());
                        sumKeep.setExpiryDate(sum.getEndDate());
                        sumKeep.setSum(Long.valueOf(sum.getSum()));
                        if(insuranceCalculations.get(0).getPlanMethod().equals("自购")){
                            sumKeep.setPlanRate("-");
                            sumKeep.setNote("自购保险");
                        }else{
                            String planRate = insuranceCalculations.get(0).getPlanRate();
                            String replace = planRate.replace("%", "");
                            divide = new BigDecimal(replace).divide(new BigDecimal(100));
                            sumKeep.setPlanRate(divide.toString());
                            sumKeep.setPremium(sum.getSumDay());
                            if(sum.getSumDay()!=null && sum.getSumDay().equals("-")){
                                sumKeep.setNote("保险起保日期超出有效期限");
                            }
                        }
                        sumKeep.setPlanMethod(insuranceCalculations.get(0).getPlanMethod());
                        if(StringUtils.isNotEmpty(sum.getTempLimit()) && sum.getTempLimit().equals("Y") ){
                            sumKeep.setTempLimit(sum.getTempLimit());
                        }else{
                            sumKeep.setTempLimit(null);
                        }
                        sumKeep.setInsuranceNo(sum.getInsuranceNo());
                        newSumKeepService.insertNewSumKeepHis(sumKeep);
                        if(insuranceCalculations.get(0).getPlanMethod().equals("缴纳保费")){
                            insuranceAddressMapper.deleteInsuranceAddressHisByInfo(wfsLimitSetUpdto.getInstanceId());
                            billingInformationMapper.deleteBillingInformationHisByInfo(wfsLimitSetUpdto.getInstanceId());
                            billingInformationMapper.deleteBillingInformationHisByReceiver(wfsLimitSetUpdto.getInstanceId());

                            //插入报表
                            //h_declaration_address
                            List<Map<String,Object>> declarationMap = reportInsuranceMapper.getInfoDeclaration(sum.getDealerName());
                            for (Map<String, Object> declaration : declarationMap) {
                                declaration.put("instanceId",wfsLimitSetUpdto.getInstanceId());
                                InsuranceAddress insuranceAddress = JSONObject.parseObject(JSONObject.toJSONString(declaration), InsuranceAddress.class);
                                insuranceAddressMapper.insertInsuranceAddressHisByInfo(insuranceAddress);
                            }
                            //h_invoicing_information
                            List<Map<String,Object>> informationMap = reportInsuranceMapper.getInfoInformation(sum.getDealerName());
                            for (Map<String, Object> information : informationMap) {
                                information.put("instanceId",wfsLimitSetUpdto.getInstanceId());
                                BillingInformation billingInformation = JSONObject.parseObject(JSONObject.toJSONString(information), BillingInformation.class);
                                billingInformationMapper.insertBillingInformationHisByInfo(billingInformation);

                            }
                            //h_invoice_address
                            List<Map<String,Object>> addressMap = reportInsuranceMapper.getInfoAddress(sum.getDealerName());
                            for (Map<String, Object> address : addressMap) {
                                address.put("instanceId",wfsLimitSetUpdto.getInstanceId());
                                BillingInformation addressInfo = JSONObject.parseObject(JSONObject.toJSONString(address), BillingInformation.class);
                                billingInformationMapper.insertBillingInformationHisByReceiver(addressInfo);
                            }

                        }

                        //查询是否满足合并条件，满足则合并，否则则插入新记录
                        if(insuranceCalculations.get(0).getPlanMethod().equals("自购")){
                            NewSumKeep sumKeepTemp = new NewSumKeep();
                            sumKeepTemp.setDealerName(sumKeep.getDealerName());
                            sumKeepTemp.setSector(sumKeep.getSector());
                            sumKeepTemp.setExpiryDate(sumKeep.getExpiryDate());
                            if(StringUtils.isNotEmpty(sum.getTempLimit()) && sum.getTempLimit().equals("Y")){
                                sumKeepTemp.setTempLimit(sum.getTempLimit());
                            }
                            List<NewSumKeep> newSumKeeps = newSumKeepMapper.selectNewSumKeepList2(sumKeepTemp);
                            if(newSumKeeps!=null && newSumKeeps.size()>0){
                                //合并
                                NewSumKeep newSumKeep1 = newSumKeeps.get(0);
                                newSumKeep1.setSum(sumKeep.getSum()+newSumKeep1.getSum());
                                newSumKeep1.setEffectiveDate(sumKeep.getEffectiveDate());
                                newSumKeepMapper.updateNewSumKeep(newSumKeep1);
                            }else{
                                newSumKeepService.insertNewSumKeep(sumKeep);
                                annualReviewyService.saveDbLog("1","新增保险历史记录",null ,wfsLimitSetUpdto.getInstanceId(),null,sumKeep,null);
                            }
                        }else{
                            NewSumKeep sumKeepTemp = new NewSumKeep();
                            sumKeepTemp.setDealerName(sumKeep.getDealerName());
                            sumKeepTemp.setSector(sumKeep.getSector());
                            sumKeepTemp.setPlanRate(sumKeep.getPlanRate());
                            sumKeepTemp.setExpiryDate(sumKeep.getExpiryDate());
                            if(StringUtils.isNotEmpty(sum.getTempLimit()) && sum.getTempLimit().equals("Y")){
                                sumKeepTemp.setTempLimit(sum.getTempLimit());
                            }
                            List<NewSumKeep> newSumKeeps = newSumKeepMapper.selectNewSumKeepList2(sumKeepTemp);
                            if(newSumKeeps!=null && newSumKeeps.size()>0){
                                //合并
                                for (NewSumKeep newSumKeep : newSumKeeps) {
                                    newSumKeep.setSum(sumKeep.getSum()+newSumKeep.getSum());
                                    newSumKeep.setEffectiveDate(sumKeep.getEffectiveDate());
                                    newSumKeepMapper.updateNewSumKeep(newSumKeep);
                                }
                            }else{
                                newSumKeepService.insertNewSumKeep(sumKeep);
                                annualReviewyService.saveDbLog("1","新增保险历史记录",null ,wfsLimitSetUpdto.getInstanceId(),null,sumKeep,null);
                            }
                        }
                        ReportInsurance reportInsurance = new ReportInsurance();
                        reportInsurance.setInstanceId(wfsLimitSetUpdto.getInstanceId());
                        reportInsurance.setDealerName(sum.getDealerName());
                        reportInsurance.setSector(sum.getSector());
                        reportInsurance.setEffectiveDate(sum.getStartDate());
                        reportInsurance.setExpiryDate(sum.getEndDate());
                        reportInsurance.setCoverage(sum.getSum());
                        reportInsurance.setInsuranceNo(sum.getInsuranceNo());
                        if(insuranceCalculations.get(0).getPlanMethod().equals("自购")){
                            reportInsurance.setNote("自购保险");
                            reportInsurance.setRate("-");
                        }else{
                            if(sum.getSumDay()!=null && sum.getSumDay().equals("-")){
                                reportInsurance.setNote("保险起保日期超出有效期限");
                            }
                            reportInsurance.setRate(divide.toString());
                            reportInsurance.setPremium(sum.getSumDay());
                        }
                        reportInsurance.setTempLimit(sum.getTempLimit());
                        ReportInsuranceMapper bean = SpringUtils.getBean(ReportInsuranceMapper.class);
                        bean.insertReportInsurance(reportInsurance);
                        annualReviewyService.saveDbLog("1","新增保险报表记录",null ,wfsLimitSetUpdto.getInstanceId(),null,reportInsurance,null);

                        if(insuranceCalculations.get(0).getPlanMethod().equals("缴纳保费")){
                            ReportInsuranceThree reportInsuranceThree = new ReportInsuranceThree();
                            reportInsuranceThree.setDealerName(sum.getDealerName());
                            reportInsuranceThree.setSector(sum.getSector());
                            reportInsuranceThree.setInstanceId(wfsLimitSetUpdto.getInstanceId());
                            reportInsuranceThree.setPremium(sum.getSumDay());
                            List<InsuranceDeclarationInfo> insuranceDeclarationInfos = wfsLimitSetUpdto.getInsuranceDeclarationInfo();
                            if(CollectionUtil.isNotEmpty(insuranceDeclarationInfos)){
                                reportInsuranceThree.setBankFeedbackNo(insuranceDeclarationInfos.get(0).getBankFeedbackNo());
                                reportInsuranceThree.setPremiumReceivedDate(insuranceDeclarationInfos.get(0).getPremiumReceivedDate());
                                reportInsuranceThree.setReceivedAmount(insuranceDeclarationInfos.get(0).getReceivedAmount());
                                reportInsuranceThree.setNoteOne(insuranceDeclarationInfos.get(0).getNote());
                            }
                            ReportInsuranceThreeMapper bean1 = SpringUtils.getBean(ReportInsuranceThreeMapper.class);
                            bean1.insertReportInsuranceThree(reportInsuranceThree);
                            annualReviewyService.saveDbLog("1","新增保险报表记录",null ,wfsLimitSetUpdto.getInstanceId(),null,reportInsuranceThree,null);
                        }
                    }
                }

            }
        }else if(wfsLimitSetUpdto.getIsAdopt()!= null && wfsLimitSetUpdto.getIsAdopt()==2 &&wfsLimitSetUpdto.getName().equals("保证金调整确认")  && wfsLimitSetUpdto.getDepositCalculationList()!=null
                && wfsLimitSetUpdto.getDepositCalculationList().size()>0){

            if(wfsLimitSetUpdto.getDepositDeclarationInfo()!=null && wfsLimitSetUpdto.getDepositDeclarationInfo().size()>0){
                for (InsuranceDeclarationInfo insuranceDeclarationInfo : wfsLimitSetUpdto.getDepositDeclarationInfo()) {
                    if(insuranceDeclarationInfo.getPremiumReceivedDate()!=null &&  insuranceDeclarationInfo.getFlag() == null ){
                        insuranceDeclarationInfo.setId(IdUtils.simpleUUID());
                        insuranceDeclarationInfo.setInstanceId(wfsLimitSetUpdto.getInstanceId());
                        insuranceDeclarationInfo.setFlag(10);
                        if(StringUtils.isNotEmpty(insuranceDeclarationInfo.getReceivedAmount())){
                            String receivedAmount = insuranceDeclarationInfo.getReceivedAmount();
                            String replace = receivedAmount.replace(",", "");
                            BigDecimal bigDecimal = new BigDecimal(replace);
                            String amt = NumberFormat.getNumberInstance().format(bigDecimal);
                            insuranceDeclarationInfo.setReceivedAmount(amt);
                        }
                        insuranceDeclarationInfoService.insertDepositDeclarationInfo(insuranceDeclarationInfo);

                        //插入保证金报表2
                        BigDecimal  zero  = BigDecimal.ZERO;
                        for (DepositCalculation depositCalculation : wfsLimitSetUpdto.getDepositCalculationList()) {
                            if(depositCalculation.getGap() !=null && !("".equals(depositCalculation.getGap()))) {
                                String amt = depositCalculation.getGap().replace(",", "");
                                if(new BigDecimal(amt).compareTo(new BigDecimal(0))>0){
                                    zero = zero.add(new BigDecimal(amt));
                                }
                            }
                        }
                        ReportDepositTow reportDepositTow = new ReportDepositTow();
                        reportDepositTow.setId(IdUtils.simpleUUID());
                        reportDepositTow.setInstanceId(wfsLimitSetUpdto.getInstanceId());
                        reportDepositTow.setDealerName(wfsLimitSetUpdto.getDepositCalculationList().get(0).getDealerName());
                        if(zero.compareTo(new BigDecimal(0))>0){
                            reportDepositTow.setDepositGap(zero.toString());
                        }else{
                            reportDepositTow.setDepositGap("");
                        }
                        reportDepositTow.setSector(wfsLimitSetUpdto.getDepositCalculationList().get(0).getSector());
                        reportDepositTow.setBankFeedbackNo(insuranceDeclarationInfo.getBankFeedbackNo());
                        reportDepositTow.setDepositReceivedDate(insuranceDeclarationInfo.getPremiumReceivedDate());
                        reportDepositTow.setReceivedAmount(insuranceDeclarationInfo.getReceivedAmount());
                        reportDepositTow.setNote(insuranceDeclarationInfo.getNote());
                        reportDepositTowMapper.insertReportDepositTow(reportDepositTow);
                    }
                }
            }
            //保证金调整确认report
            DepositCalculation depositCalculation1 = new DepositCalculation();
            depositCalculation1.setInstanceId(wfsLimitSetUpdto.getInstanceId());
            List<DepositCalculation> depositCalculations = depositCalculationService.selectDepositCalculationList(depositCalculation1);
            List<DepositCalculation> depositCalculationList = wfsLimitSetUpdto.getDepositCalculationList();
            //保证金调整确认 op确认时间
            for (DepositCalculation depositCalculation : depositCalculations) {
                //TODO 流程九数据插入
                if (depositCalculation.getGap() != null &&  !depositCalculation.getGap().equals("0.00")) {
                    String amt = depositCalculation.getGap().replace(",", "");
                    depositCalculation.setGap(amt);
                    String NewBalanceAmount = null ;
                    if(depositCalculation.getProcess()!="Keep"){
                        for (DepositCalculation calculation : depositCalculationList) {
                            if(calculation.getId().equals(depositCalculation.getId())){
                                NewBalanceAmount = calculation.getCurrentAmount();
                            }
                        }
                        ReportDeposit reportDeposit = new ReportDeposit();
                        reportDeposit.setId(IdUtils.simpleUUID());
                        reportDeposit.setInstanceId(wfsLimitSetUpdto.getInstanceId());
                        reportDeposit.setDealerCode(depositCalculation.getDealerCode());
                        reportDeposit.setDealerName(depositCalculation.getDealerName());
                        reportDeposit.setRequestDate(annualReviewy1.getCreateTime());
                        reportDeposit.setOldBalanceAmount(depositCalculation.getCurrentAmount());
                        reportDeposit.setNewBalanceAmount(NewBalanceAmount);
                        //保证金调整确认 op确认时间
                        reportDeposit.setProcessingDate(new Date());
                        reportDeposit.setRequestType(depositCalculation.getProcess());
                        if (depositCalculation.getLimitType().equals("DEMO") || depositCalculation.getLimitType().equals("NORMAL") || depositCalculation.getLimitType().equals("NORMAL/DEMO/TEMP")) {
                            reportDeposit.setDepositType("RD");
                        } else if (depositCalculation.getLimitType().equalsIgnoreCase("CB")) {
                            reportDeposit.setDepositType("CBDP");
                        }else if (depositCalculation.getLimitType().equalsIgnoreCase("PART")) {
                            reportDeposit.setDepositType("PATDP");
                        } else if (depositCalculation.getLimitType().equalsIgnoreCase("USED")) {
                            reportDeposit.setDepositType("UDDP");
                        }
                        int i = new BigDecimal(depositCalculation.getGap()).compareTo(new BigDecimal(0));

                        if (i == -1) {
                            reportDeposit.setRequestAmount(depositCalculation.getTransferAmount());
                        } else if (i == 1) {
                            reportDeposit.setRequestType("Deposit increase");
                            reportDeposit.setRequestAmount(depositCalculation.getGap());
                        }
                        if (StringUtils.isNotEmpty(depositCalculation.getTransferTo())) {
                            String[] split = depositCalculation.getTransferTo().split("-");
                            reportDeposit.setTransferToDealerCode(split[0]);
                            reportDeposit.setTransferToDealerName(split[1]);
                        }

                        reportDeposit.setCreateTime(new Date());
                        reportDeposit.setCreateBy(SecurityUtils.getUsername());
                        SpringUtils.getBean(ReportDepositMapper.class).insertReportDeposit(reportDeposit);
                        annualReviewyService.saveDbLog("1","新增保证金报表记录",null ,wfsLimitSetUpdto.getInstanceId(),null,reportDeposit,null);


                    }

                }
            }

        }else if(wfsLimitSetUpdto.getIsAdopt()!= null && wfsLimitSetUpdto.getIsAdopt()==2 &&wfsLimitSetUpdto.getName().equals("盈余保证金操作")  && wfsLimitSetUpdto.getDepositCalculationList()!=null
                && wfsLimitSetUpdto.getDepositCalculationList().size()>0){
            //保证金调整确认report
            DepositCalculation depositCalculation1 = new DepositCalculation();
            depositCalculation1.setInstanceId(wfsLimitSetUpdto.getInstanceId());
            List<DepositCalculation> depositCalculations = depositCalculationService.selectDepositCalculationList(depositCalculation1);
            List<DepositCalculation> depositCalculationList = wfsLimitSetUpdto.getDepositCalculationList();
            //保证金调整确认 op确认时间
            for (DepositCalculation depositCalculation : depositCalculations) {
                if (StringUtils.isNotEmpty(depositCalculation.getProcess()) && depositCalculation.getProcess().equals("Transfer")) {
                    ReportDeposit reportDeposit = new ReportDeposit();
                    reportDeposit.setId(IdUtils.simpleUUID());
                    reportDeposit.setInstanceId(wfsLimitSetUpdto.getInstanceId());
                    reportDeposit.setDealerCode(depositCalculation.getDealerCode());
                    reportDeposit.setDealerName(depositCalculation.getDealerName());
                    reportDeposit.setRequestDate(annualReviewy1.getCreateTime());
                    reportDeposit.setOldBalanceAmount(depositCalculation.getOldAmount());
                    reportDeposit.setNewBalanceAmount(depositCalculation.getNewAmount());
                    reportDeposit.setToOldBalanceAmount(depositCalculation.getTransferOldAmount());
                    reportDeposit.setToNewBalanceAmount(depositCalculation.getTransferNewAmount());
                    //保证金调整确认 op确认时间
                    reportDeposit.setProcessingDate(new Date());
                    reportDeposit.setRequestType(depositCalculation.getProcess());
                    if (depositCalculation.getLimitType().equals("DEMO") || depositCalculation.getLimitType().equals("NORMAL") || depositCalculation.getLimitType().equals("NORMAL/DEMO/TEMP")) {
                        reportDeposit.setDepositType("RD");
                    } else if (depositCalculation.getLimitType().equalsIgnoreCase("CB")) {
                        reportDeposit.setDepositType("CBDP");
                    } else if (depositCalculation.getLimitType().equalsIgnoreCase("PART")) {
                        reportDeposit.setDepositType("PATDP");
                    } else if (depositCalculation.getLimitType().equalsIgnoreCase("USED")) {
                        reportDeposit.setDepositType("UDDP");
                    }
                    if (depositCalculation.getTransfertolimittype().equals("DEMO") || depositCalculation.getTransfertolimittype().equals("NORMAL") || depositCalculation.getTransfertolimittype().equals("NORMAL/DEMO/TEMP")) {
                        reportDeposit.setToDepositType("RD");
                    } else if (depositCalculation.getTransfertolimittype().equalsIgnoreCase("CB")) {
                        reportDeposit.setToDepositType("CBDP");
                    }else if (depositCalculation.getTransfertolimittype().equalsIgnoreCase("PART")) {
                        reportDeposit.setToDepositType("PATDP");
                    }else if (depositCalculation.getTransfertolimittype().equalsIgnoreCase("USED")) {
                        reportDeposit.setToDepositType("UDDP");
                    }
                    reportDeposit.setRequestAmount(depositCalculation.getTransferAmount());
                    if (StringUtils.isNotEmpty(depositCalculation.getTransferTo())) {
                        String[] split = depositCalculation.getTransferTo().split("-");
                        reportDeposit.setTransferToDealerCode(split[0]);
                        reportDeposit.setTransferToDealerName(split[1]);
                    }

                    reportDeposit.setCreateTime(new Date());
                    reportDeposit.setCreateBy(SecurityUtils.getUsername());
                    SpringUtils.getBean(ReportDepositMapper.class).insertReportDeposit(reportDeposit);
                }else if(StringUtils.isNotEmpty(depositCalculation.getProcess()) && depositCalculation.getProcess().equals("Refund to suspense")){
                    ReportDeposit reportDeposit = new ReportDeposit();
                    reportDeposit.setId(IdUtils.simpleUUID());
                    reportDeposit.setInstanceId(wfsLimitSetUpdto.getInstanceId());
                    reportDeposit.setDealerCode(depositCalculation.getDealerCode());
                    reportDeposit.setDealerName(depositCalculation.getDealerName());
                    reportDeposit.setRequestDate(annualReviewy1.getCreateTime());
                    reportDeposit.setOldBalanceAmount(depositCalculation.getOldAmount());
                    reportDeposit.setNewBalanceAmount(depositCalculation.getNewAmount());
                    //保证金调整确认 op确认时间
                    reportDeposit.setProcessingDate(new Date());
                    reportDeposit.setRequestType(depositCalculation.getProcess());
                    if (depositCalculation.getLimitType().equals("DEMO") || depositCalculation.getLimitType().equals("NORMAL") || depositCalculation.getLimitType().equals("NORMAL/DEMO/TEMP")) {
                        reportDeposit.setDepositType("RD");
                    } else if (depositCalculation.getLimitType().equalsIgnoreCase("CB")) {
                        reportDeposit.setDepositType("CBDP");
                    } else if (depositCalculation.getLimitType().equalsIgnoreCase("PART")) {
                        reportDeposit.setDepositType("PATDP");
                    } else if (depositCalculation.getLimitType().equalsIgnoreCase("USED")) {
                        reportDeposit.setDepositType("UDDP");
                    }
                    reportDeposit.setRequestAmount(depositCalculation.getTransferAmount());
                    reportDeposit.setCreateTime(new Date());
                    reportDeposit.setCreateBy(SecurityUtils.getUsername());
                    SpringUtils.getBean(ReportDepositMapper.class).insertReportDeposit(reportDeposit);
                }

            }
        }

        Notes notes = notesMapper.selectNotesByInstanceId(wfsLimitSetUpdto.getInstanceId());
        if(wfsLimitSetUpdto.getComments() !=null ){
            notes.setComments(wfsLimitSetUpdto.getComments());
        }
        if(wfsLimitSetUpdto.getConditionNotes() !=null ){
            notes.setConditionNotes(wfsLimitSetUpdto.getConditionNotes());
        }
        notesMapper.updateNotes(notes);
        wfsLimitSetUpdto.setComments(notes.getComments());
        wfsLimitSetUpdto.setConditionNotes(notes.getConditionNotes());

        if(wfsLimitSetUpdto.getInsuranceDeclarationInfo() !=null &&  wfsLimitSetUpdto.getInsuranceDeclarationInfo().size()>0){
            List<InsuranceDeclarationInfo> insuranceDeclarationInfoList = wfsLimitSetUpdto.getInsuranceDeclarationInfo();
            InsuranceDeclarationInfo insuranceDeclarationInfo = insuranceDeclarationInfoList.get(0);
            if(insuranceDeclarationInfo.getId() !=null ){
                InsuranceDeclarationInfo insuranceDeclarationInfo1 = insuranceDeclarationInfoService.selectInsuranceDeclarationInfoById(insuranceDeclarationInfo.getId());
                insuranceDeclarationInfoService.updateInsuranceDeclarationInfo(insuranceDeclarationInfo);
                annualReviewyService.saveDbLog("3","修改表单信息","保险信息确认" ,wfsLimitSetUpdto.getInstanceId(),insuranceDeclarationInfo1,insuranceDeclarationInfo,null);

            }else{
                insuranceDeclarationInfo.setId(IdUtils.simpleUUID());
                insuranceDeclarationInfo.setInstanceId(wfsLimitSetUpdto.getInstanceId());
                insuranceDeclarationInfoService.insertInsuranceDeclarationInfo(insuranceDeclarationInfo);
                annualReviewyService.saveDbLog("1","新增表单信息","保险信息确认",wfsLimitSetUpdto.getInstanceId(),null,insuranceDeclarationInfo,null);

            }
        }

        if (wfsLimitSetUpdto.getTemporaryConditionFollowUpList() != null) {
            for (TemporaryConditionFollowUp temporaryConditionFollowUp : wfsLimitSetUpdto.getTemporaryConditionFollowUpList()) {
                if(temporaryConditionFollowUp.getId() ==null){
                    temporaryConditionFollowUp.setId(IdUtils.simpleUUID());
                    temporaryConditionFollowUp.setInstanceId(wfsLimitSetUpdto.getInstanceId());
                    temporaryConditionFollowUpMapper.insertTemporaryConditionFollowUp(temporaryConditionFollowUp);
                    annualReviewyService.saveDbLog("1","新增表单信息","TEMPORARY CONDITION FOLLOW UP",wfsLimitSetUpdto.getInstanceId(),null,temporaryConditionFollowUp,null);

                }else{
                    TemporaryConditionFollowUp temporaryConditionFollowUp1 = temporaryConditionFollowUpMapper.selectTemporaryConditionFollowUpById(temporaryConditionFollowUp.getId());
                    temporaryConditionFollowUpMapper.updateTemporaryConditionFollowUp(temporaryConditionFollowUp);
                    annualReviewyService.saveDbLog("3","修改表单信息","TEMPORARY CONDITION FOLLOW UP",wfsLimitSetUpdto.getInstanceId(),temporaryConditionFollowUp1,temporaryConditionFollowUp,null);
                }

            }
        }

        if (wfsLimitSetUpdto.getLimitSetupResult() != null) {
            //先删后插
            HLimitSetupResult hLimitSetupResult = new HLimitSetupResult();
            hLimitSetupResult.setInstanceid(wfsLimitSetUpdto.getInstanceId());
            List<HLimitSetupResult> hLimitSetupResults = limitSetupResultService.selectHLimitSetupResultList(hLimitSetupResult);
            for (HLimitSetupResult limitSetupResult : hLimitSetupResults) {
                limitSetupResultService.deleteHLimitSetupResultById(limitSetupResult.getId());
                annualReviewyService.saveDbLog("2","删除表单信息","LIMIT SET-UP RESULT",wfsLimitSetUpdto.getInstanceId(),limitSetupResult,null,null);

            }

            for (HLimitSetupResult limitSetupResult : wfsLimitSetUpdto.getLimitSetupResult()) {
                limitSetupResult.setInstanceid(wfsLimitSetUpdto.getInstanceId());
                limitSetupResultService.insertHLimitSetupResult(limitSetupResult);
                annualReviewyService.saveDbLog("1","新增表单信息","LIMIT SET-UP RESULT",wfsLimitSetUpdto.getInstanceId(),null,limitSetupResult,null);

            }
        }
        if (wfsLimitSetUpdto.getLimitActiveProposalList() != null) {
            for (LimitActiveProposal limitActiveProposal : wfsLimitSetUpdto.getLimitActiveProposalList()) {
                if(limitActiveProposal.getId() !=null){
                    System.out.println(limitActiveProposal);
                    LimitActiveProposal limitActiveProposal1 = limitActiveProposalService.selectLimitActiveProposalById(limitActiveProposal.getId());
                    String amt = limitActiveProposal.getProposalActiveLimit().replace(",", "");
                    limitActiveProposal.setProposalActiveLimit(Long.valueOf(amt).toString());
                    limitActiveProposalService.updateLimitActiveProposal(limitActiveProposal);
                    annualReviewyService.saveDbLog("3","修改表单信息","LIMIT SET-UP PROPOSAL",wfsLimitSetUpdto.getInstanceId(),limitActiveProposal1,limitActiveProposal,null);

                }
            }
        }

        BigDecimal GAP = null;
        BigDecimal TOTAL = null;
        if (wfsLimitSetUpdto.getDepositCalculationList() != null) {
            for (DepositCalculation depositCalculation : wfsLimitSetUpdto.getDepositCalculationList()) {
                if(depositCalculation.getId() !=null){
                    DepositCalculation depositCalculation1 = depositCalculationService.selectDepositCalculationById(depositCalculation.getId());
                    depositCalculationService.updateDepositCalculation(depositCalculation);
                    annualReviewyService.saveDbLog("3","修改表单信息","DEPOSIT CALCULATION" ,wfsLimitSetUpdto.getInstanceId(),depositCalculation1,depositCalculation,null);

                }
                if(depositCalculation.getGap() !=null && !("".equals(depositCalculation.getGap()))){
                    if(GAP == null){
                        String amt = depositCalculation.getGap().replace(",", "");
                        GAP = new BigDecimal(amt);
                    }else{
                        if(new BigDecimal(depositCalculation.getGap()).compareTo(GAP)==1){
                            String amt = depositCalculation.getGap().replace(",", "");
                            GAP = new BigDecimal(amt);
                        }
                    }
                }
            }
        }

        if(wfsLimitSetUpdto.getInsuranceCalculationList()!=null) {
            for (InsuranceCalculation insuranceCalculation : wfsLimitSetUpdto.getInsuranceCalculationList()) {
                if(insuranceCalculation.getId()!=null){
                    if(insuranceCalculation.getPlanMethod().equals("自购")){
                        insuranceCalculation.setPlanRate("");
                    }
                    InsuranceCalculation insuranceCalculation1 = insuranceCalculationService.selectInsuranceCalculationById(insuranceCalculation.getId());
                    insuranceCalculationService.updateInsuranceCalculation(insuranceCalculation);
                    annualReviewyService.saveDbLog("3","修改表单信息","INSURANCE CALCULATION" ,wfsLimitSetUpdto.getInstanceId(),insuranceCalculation1,insuranceCalculation,null);

                }
                if(insuranceCalculation.getPlanTotal() !=null &&  !("".equals(insuranceCalculation.getPlanTotal()))){
                    if(insuranceCalculation.getPlanTotal().equals("-")){
                        TOTAL = new BigDecimal(100);
                    }else{
                        if(TOTAL == null){
                            TOTAL = new BigDecimal(insuranceCalculation.getPlanTotal());
                        }else{
                            if(new BigDecimal(insuranceCalculation.getPlanTotal()).compareTo(TOTAL)==1){
                                TOTAL = new BigDecimal(insuranceCalculation.getPlanTotal());
                            }
                        }
                    }
                }
            }
        }

        if(wfsLimitSetUpdto.getInsuranceAddressList()!=null){
            for (InsuranceAddress insuranceAddress : wfsLimitSetUpdto.getInsuranceAddressList()) {
                if(insuranceAddress.getId()!=null){
                    InsuranceAddress insuranceAddress1 = insuranceAddressService.selectInsuranceAddressById(insuranceAddress.getId());
                    insuranceAddressService.updateInsuranceAddress(insuranceAddress);
                    //annualReviewyService.saveDbLog("3","修改表单信息","保险申报地址",wfsLimitSetUpdto.getInstanceId(),insuranceAddress1,insuranceAddress,null);

                }else{
                    insuranceAddress.setId(IdUtils.simpleUUID());
                    insuranceAddress.setInstanceId(wfsLimitSetUpdto.getInstanceId());
                    insuranceAddressService.insertInsuranceAddress(insuranceAddress);
                   // annualReviewyService.saveDbLog("1","新增表单信息","保险申报地址",wfsLimitSetUpdto.getInstanceId(),null,insuranceAddress,null);

                }

            }
        }

        if(wfsLimitSetUpdto.getSelfplanInformationList()!=null){
            for (SelfplanInformation selfplanInformation : wfsLimitSetUpdto.getSelfplanInformationList()) {
                if(selfplanInformation.getId()!=null){
                    selfplanInformationService.updateSelfplanInformation(selfplanInformation);
                }else{
                    selfplanInformation.setId(IdUtils.simpleUUID());
                    selfplanInformation.setInstanceId(wfsLimitSetUpdto.getInstanceId());
                    selfplanInformationService.insertSelfplanInformation(selfplanInformation);
                }

            }
        }

        if(wfsLimitSetUpdto.getBillingInformationList()!=null){
            for (BillingInformation billingInformation : wfsLimitSetUpdto.getBillingInformationList()) {
                if(billingInformation.getId()!=null){
                    BillingInformation billingInformation1 = billingInformationService.selectBillingInformationById(billingInformation.getId());
                    if(billingInformation1!=null){
                        annualReviewyService.saveDbLog("3","修改表单信息","开票信息",wfsLimitSetUpdto.getInstanceId(),billingInformation1,billingInformation,null);
                    }
                    billingInformationService.updateBillingInformation(billingInformation);
                }else{
                    billingInformation.setId(IdUtils.simpleUUID());
                    billingInformation.setInstanceId(wfsLimitSetUpdto.getInstanceId());
                    billingInformationService.insertBillingInformation(billingInformation);
                    annualReviewyService.saveDbLog("1","新增表单信息","开票信息",wfsLimitSetUpdto.getInstanceId(),null,billingInformation,null);

                }
            }
        }

        if(wfsLimitSetUpdto.getNewSumList()!=null){
            for (NewSum newSum : wfsLimitSetUpdto.getNewSumList()) {
                if(newSum.getId()!=null){
                    NewSum newSum1 = newSumService.selectNewSumById(newSum.getId());
                    if(newSum1 ==null){
                        newSum.setId(IdUtils.simpleUUID());
                        newSum.setInstanceId(wfsLimitSetUpdto.getInstanceId());
                        newSumService.insertNewSum(newSum);
                    }else{
                        newSumService.updateNewSum(newSum);
                    }
                }else{
                    newSum.setId(IdUtils.simpleUUID());
                    newSum.setInstanceId(wfsLimitSetUpdto.getInstanceId());
                    newSumService.insertNewSum(newSum);
                    annualReviewyService.saveDbLog("1","新增表单信息","新额度需要的保险",wfsLimitSetUpdto.getInstanceId(),null,newSum,null);

                }

            }
        }

        if(wfsLimitSetUpdto.getPaidSumList()!=null){
            for (PaidSum paidSum : wfsLimitSetUpdto.getPaidSumList()) {
                if(paidSum.getId()!=null){
                    PaidSum paidSum1 = paidSumService.selectPaidSumById(paidSum.getId());
                    if(paidSum1 == null ){
                        paidSum.setId(IdUtils.simpleUUID());
                        paidSum.setInstanceId(wfsLimitSetUpdto.getInstanceId());
                        paidSumService.insertPaidSum(paidSum);
                    }else{
                        paidSumService.updatePaidSum(paidSum);
                    }

                }else{
                    paidSum.setId(IdUtils.simpleUUID());
                    paidSum.setInstanceId(wfsLimitSetUpdto.getInstanceId());
                    paidSumService.insertPaidSum(paidSum);
                    annualReviewyService.saveDbLog("1","新增表单信息","因保险方案变更需补缴的保费",wfsLimitSetUpdto.getInstanceId(),null,paidSum,null);

                }

            }
        }

        List<Fileupload> application = wfsLimitSetUpdto.getApplication();
        System.out.println("applications==" + application);
        if (application != null && application.size() > 0) {
            for (Fileupload filesVO : application) {
                if(filesVO.getId() ==null){
                    Fileupload fileupload = new Fileupload();
                    fileupload.setFileName(filesVO.getFileName());
                    fileupload.setOriginalFileName(filesVO.getName());
                    fileupload.setName(filesVO.getName());
                    fileupload.setUrl(filesVO.getUrl());
                    fileupload.setId(IdUtils.simpleUUID());
                    fileupload.setInstanceId(wfsLimitSetUpdto.getInstanceId());
                    fileupload.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                    fileupload.setCreateName(SecurityUtils.getNickName());
                    fileupload.setCreateTime(new Date());
                    fileupload.setType("application");
                    fileuploadService.insertFileupload(fileupload);
                }

            }
        }
        List<Fileupload> information = wfsLimitSetUpdto.getInformation();
        System.out.println("informations==" + information);
        if (information != null && information.size() > 0) {
            for (Fileupload filesVO : information) {
                if(filesVO.getId() ==null){
                    Fileupload fileupload = new Fileupload();
                    fileupload.setFileName(filesVO.getFileName());
                    fileupload.setOriginalFileName(filesVO.getName());
                    fileupload.setName(filesVO.getName());
                    fileupload.setUrl(filesVO.getUrl());
                    fileupload.setId(IdUtils.simpleUUID());
                    fileupload.setInstanceId(wfsLimitSetUpdto.getInstanceId());
                    fileupload.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                    fileupload.setCreateName(SecurityUtils.getNickName());
                    fileupload.setCreateTime(new Date());
                    fileupload.setType("information");
                    fileuploadService.insertFileupload(fileupload);
                }

            }
        }

        List<Fileupload> financials = wfsLimitSetUpdto.getFinancials();
        System.out.println("financialss==" + financials);
        if (financials != null && financials.size() > 0) {
            for (Fileupload filesVO : financials) {
                if(filesVO.getId() ==null){
                    Fileupload fileupload = new Fileupload();
                    fileupload.setFileName(filesVO.getFileName());
                    fileupload.setOriginalFileName(filesVO.getName());
                    fileupload.setName(filesVO.getName());
                    fileupload.setUrl(filesVO.getUrl());
                    fileupload.setId(IdUtils.simpleUUID());
                    fileupload.setInstanceId(wfsLimitSetUpdto.getInstanceId());
                    fileupload.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                    fileupload.setCreateName(SecurityUtils.getNickName());
                    fileupload.setCreateTime(new Date());
                    fileupload.setType("financials");
                    fileuploadService.insertFileupload(fileupload);
                }

            }
        }

        List<Fileupload> guarantee = wfsLimitSetUpdto.getGuarantee();
        System.out.println("guarantees==" + guarantee);
        if (guarantee != null && guarantee.size() > 0) {
            for (Fileupload filesVO : guarantee) {
                if(filesVO.getId() ==null){
                    Fileupload fileupload = new Fileupload();
                    fileupload.setFileName(filesVO.getFileName());
                    fileupload.setOriginalFileName(filesVO.getName());
                    fileupload.setName(filesVO.getName());
                    fileupload.setUrl(filesVO.getUrl());
                    fileupload.setId(IdUtils.simpleUUID());
                    fileupload.setInstanceId(wfsLimitSetUpdto.getInstanceId());
                    fileupload.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                    fileupload.setCreateName(SecurityUtils.getNickName());
                    fileupload.setCreateTime(new Date());
                    fileupload.setType("guarantee");
                    fileuploadService.insertFileupload(fileupload);
                }

            }
        }
        List<Fileupload> corporate = wfsLimitSetUpdto.getCorporate();
        System.out.println("corporates==" + corporate);
        if (corporate != null && corporate.size() > 0) {
            for (Fileupload filesVO : corporate) {
                if(filesVO.getId() ==null){
                    Fileupload fileupload = new Fileupload();
                    fileupload.setFileName(filesVO.getFileName());
                    fileupload.setOriginalFileName(filesVO.getName());
                    fileupload.setName(filesVO.getName());
                    fileupload.setUrl(filesVO.getUrl());
                    fileupload.setId(IdUtils.simpleUUID());
                    fileupload.setInstanceId(wfsLimitSetUpdto.getInstanceId());
                    fileupload.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                    fileupload.setCreateName(SecurityUtils.getNickName());
                    fileupload.setCreateTime(new Date());
                    fileupload.setType("corporate");
                    fileuploadService.insertFileupload(fileupload);
                }

            }
        }

        List<Fileupload> other = wfsLimitSetUpdto.getOther();
        System.out.println("others==" + other);
        if (other != null && other.size() > 0) {
            for (Fileupload filesVO : other) {
                if(filesVO.getId() ==null){
                    Fileupload fileupload = new Fileupload();
                    fileupload.setFileName(filesVO.getFileName());
                    fileupload.setOriginalFileName(filesVO.getName());
                    fileupload.setName(filesVO.getName());
                    fileupload.setUrl(filesVO.getUrl());
                    fileupload.setId(IdUtils.simpleUUID());
                    fileupload.setInstanceId(wfsLimitSetUpdto.getInstanceId());
                    fileupload.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                    fileupload.setCreateName(SecurityUtils.getNickName());
                    fileupload.setCreateTime(new Date());
                    fileupload.setType("other");
                    fileuploadService.insertFileupload(fileupload);
                }

            }
        }

        List<Fileupload> opDocument = wfsLimitSetUpdto.getOpDocument();
        if (opDocument != null && opDocument.size() > 0) {
            for (Fileupload filesVO : opDocument) {
                if(filesVO.getId() ==null){
                    Fileupload fileupload = new Fileupload();
                    fileupload.setFileName(filesVO.getFileName());
                    fileupload.setOriginalFileName(filesVO.getName());
                    fileupload.setName(filesVO.getName());
                    fileupload.setUrl(filesVO.getUrl());
                    fileupload.setId(IdUtils.simpleUUID());
                    fileupload.setInstanceId(wfsLimitSetUpdto.getInstanceId());
                    fileupload.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                    fileupload.setCreateName(SecurityUtils.getNickName());
                    fileupload.setCreateTime(new Date());
                    fileupload.setType("opDocument");
                    fileuploadService.insertFileupload(fileupload);
                }

            }
        }
        AnnualReviewy annualReviewy = annualReviewyMapper.selectAnnualReviewyByInstanceId(wfsLimitSetUpdto.getInstanceId());
        AnnualReviewy outBean = new AnnualReviewy();
        BeanUtils.copyProperties(annualReviewy,outBean);
        String UpdateBy = annualReviewy.getUpdateBy();
        if (null != UpdateBy) {
            annualReviewy.setUpdateBy(UpdateBy + "|" + SecurityUtils.getUsername());
        } else {
            annualReviewy.setUpdateBy(SecurityUtils.getUsername());
        }
        annualReviewy.setLockname(null);
        if(ObjectUtil.isNotEmpty(GAP) && ObjectUtil.isNotEmpty(GAP.longValue())){
            annualReviewy.setGAP(GAP.longValue());
        }
        if(GAP.longValue()>0){
            System.out.println("Gap 大与0");
        }
        if(TOTAL.compareTo(new BigDecimal(0)) >0){
            TOTAL  = TOTAL.add(new BigDecimal(1));
        }
        annualReviewy.setTOTAL(TOTAL.longValue());
        String title = "";
        Authentication.setAuthenticatedUserId(SecurityUtils.getLoginUser()
                .getUser()
                .getUserId()
                .toString());
        Task task = null;

        if (wfsLimitSetUpdto.getCaoGao() != null && wfsLimitSetUpdto.getCaoGao().equals("0")) {

            annualReviewy.setState("0");
            //流程开始
            if (StringUtils.isNotNull(wfsLimitSetUpdto.getName())) {
                title =  wfsLimitSetUpdto.getName();
            } else {
                title = "WFS Limit Set-Up";
            }
            ProcessInstance processInstance = null;
            if (StringUtils.isNotNull(wfsLimitSetUpdto.getProcessDefinitionKey())) {
                processInstance = processRuntime.start(ProcessPayloadBuilder
                        .start()
                        .withProcessDefinitionKey(wfsLimitSetUpdto.getProcessDefinitionKey())
                        .withName(title)
                        .withBusinessKey(wfsLimitSetUpdto.getInstanceId())
                        // .withVariable("deptLeader",join)
                        .build());
            } else {
                processInstance = processRuntime.start(ProcessPayloadBuilder
                        .start()
                        .withProcessDefinitionKey("WFSLimitSetUp_1")
                        .withName(title)
                        .withBusinessKey(wfsLimitSetUpdto.getInstanceId())
                        // .withVariable("deptLeader",join)
                        .build());
            }

            task = taskService.createTaskQuery()
                    .processInstanceId(processInstance.getId())
                    .singleResult();



            TaskQuery query = taskService.createTaskQuery().taskCandidateOrAssigned(SecurityUtils.getUsername()).active();
            List<Task> todoList = query.list();//获取申请人的待办任务列表
            for (Task tmp : todoList) {
                if (tmp.getProcessInstanceId().equals(processInstance.getId())) {
                    task = tmp;//获取当前流程实例，当前申请人的待办任务
                    break;
                }
            }
            HashMap<String, Object> variables = new HashMap<String, Object>();

            variables.put("GPA", GAP.longValue());
            variables.put("TOTAL", TOTAL.longValue());
            variables.put("FormProperty_0nfqek9",0);
            taskService.complete(task.getId(), variables);

            if(ObjectUtil.isNotEmpty(task)){
                annualReviewy.setStartNode(task.getName());
            }

            //发送邮件
            try {
                org.activiti.engine.runtime.ProcessInstance processInstanceMe = runtimeService.createProcessInstanceQuery()
                        .processInstanceId(task.getProcessInstanceId())
                        .singleResult();
                // 上一个节点的执行完，再次查询，获取下一个节点的任务信息
                List<Task> list = taskService.createTaskQuery()
                        .processInstanceId(processInstanceMe.getProcessInstanceId())
                        .list();
                for (Task task1 : list) {
                    ThreadUtil.execute(new Runnable() {

                        @Override
                        public void run() {
                            actTaskService.sendMail(task1, wfsLimitSetUpdto.getInstanceId(),null);
                        }
                    });
                }
            } catch (Exception e) {
                log.error("邮件发送失败，{}",e.getMessage());
            }

        }
        if(wfsLimitSetUpdto.getIsAdopt()!= null && wfsLimitSetUpdto.getIsAdopt()==3 && wfsLimitSetUpdto.getName() !=null && wfsLimitSetUpdto.getName().equals("UW-Approver")){
            //查询
            DealerInformation dealerInformations = dealerInformationMapper.selectInfoBySectorAndDealerName(wfsLimitSetUpdto.getSectorName(),wfsLimitSetUpdto.getDealerName());
            String distributorCode = "";
            String dealerCode = dealerInformations.getDealerCode();
            if(StringUtils.isNotEmpty(dealerCode)){
                String code = dealerCode.substring(0, 1);
                distributorCode = dictDataMapper.selectDictLabel("distributor_code", code);
            }
            StringBuffer stringBuffer = sendWfsSetUpLimit(wfsLimitSetUpdto.getLimitActiveProposalList(), wfsLimitSetUpdto.getDealerName(), wfsLimitSetUpdto.getSectorName(), dealerInformations.getDealerCode(), distributorCode,wfsLimitSetUpdto.getInstanceId());
            if(StringUtils.isNotEmpty(stringBuffer)){
                return stringBuffer.toString();
            }else{
                //更新
                HLimitSetupResult hLimitSetupResult = new HLimitSetupResult();
                hLimitSetupResult.setInstanceid(wfsLimitSetUpdto.getInstanceId());
                List<HLimitSetupResult> hLimitSetupResults = limitSetupResultService.selectHLimitSetupResultList(hLimitSetupResult);
                for (HLimitSetupResult limitSetupResult : hLimitSetupResults) {
                    LimitActiveProposal limitActiveProposalT = new LimitActiveProposal();
                    limitActiveProposalT.setInstanceId(wfsLimitSetUpdto.getInstanceId());
                    List<LimitActiveProposal> limitActiveProposals = limitActiveProposalService.selectLimitActiveProposalList(limitActiveProposalT);
                    for (LimitActiveProposal limitActiveProposal : limitActiveProposals) {
                        if(limitSetupResult.getLimittype().equals(limitActiveProposal.getLimitType()) && limitSetupResult.getSector().equals(limitActiveProposal.getSector()) ){
                            limitSetupResult.setCurrentactivelimit(limitActiveProposal.getProposalActiveLimit());
                            limitSetupResult.setCurrentactivelimitexpirydate(limitActiveProposal.getProposedEnd());
                            limitSetupResultService.updateHLimitSetupResult(limitSetupResult);
                        }
                    }
                }
                DepositDecreaseDTO depositDecreaseDTO = new DepositDecreaseDTO();
                depositDecreaseDTO.setInstanceId(wfsLimitSetUpdto.getInstanceId());
                Map<String, Object> limitActivationProposal4 = getLimitActivationProposal4(depositDecreaseDTO);
            }
            //判断是否有盈余流程，如果有的话，则需要更新转入的保证金
            //sql判断
            DepositCalculation depositCalculationSelect = new DepositCalculation();
            depositCalculationSelect.setInstanceId(wfsLimitSetUpdto.getInstanceId());
            List<DepositCalculation> depositCalculations = depositCalculationService.selectDepositCalculationList(depositCalculationSelect);

            if (depositCalculations!= null && depositCalculations.size()>0) {
                for (DepositCalculation depositCalculation : depositCalculations) {

                    if (StringUtils.isNotEmpty(depositCalculation.getTransferTo()) && StringUtils.isNotEmpty(depositCalculation.getTransfertolimittype())) {
                        try{
                            String[] split = depositCalculation.getTransferTo().split("-");
                            String DealerCode = split[0];
                            String[] str = new String[1];
                            str[0] = DealerCode;
                            ArrayList<String[]> DealerCodes = new ArrayList<>();
                            DealerCodes.add(str);
                            DepositDecreaseDTO depositDecreaseDTO = new DepositDecreaseDTO();
                            depositDecreaseDTO.setDealerCodeArr(DealerCodes);
                            AjaxResult deposit = getDeposit(depositDecreaseDTO);
                            if(deposit.get("code").toString().equals("200")){
                                Object data = deposit.get("data");
                                List<Map<String, Object>> CreditLimitMap = (List<Map<String, Object>>) data;
                                for (Map<String, Object> stringObjectMap : CreditLimitMap) {
                                    //查询
                                    if(depositCalculation.getTransfertolimittype().equals("NORMAL")){
                                        Object Deposit = stringObjectMap.get("Deposit");
                                        depositCalculation.setTransferOldAmount(Deposit.toString());
                                        depositCalculation.setOldAmount(depositCalculation.getCurrentAmount());
                                        depositCalculationService.updateDepositCalculation(depositCalculation);
                                    }else if (depositCalculation.getTransfertolimittype().equals("CB")){
                                        Object cbDeposit = stringObjectMap.get("CBDeposit");
                                        depositCalculation.setTransferOldAmount(cbDeposit.toString());
                                        depositCalculation.setOldAmount(depositCalculation.getCurrentAmount());
                                        depositCalculationService.updateDepositCalculation(depositCalculation);
                                    }else if (depositCalculation.getTransfertolimittype().equals("PART")){
                                        Object partDeposit = stringObjectMap.get("PartDeposit");
                                        depositCalculation.setTransferOldAmount(partDeposit.toString());
                                        depositCalculation.setOldAmount(depositCalculation.getCurrentAmount());
                                        depositCalculationService.updateDepositCalculation(depositCalculation);
                                    }else if (depositCalculation.getTransfertolimittype().equals("USED")){
                                        Object usedDeposit = stringObjectMap.get("UsedDeposit");
                                        depositCalculation.setTransferOldAmount(usedDeposit.toString());
                                        depositCalculation.setOldAmount(depositCalculation.getCurrentAmount());
                                        depositCalculationService.updateDepositCalculation(depositCalculation);
                                    }
                                }

                            }
                        }catch (Exception e){
                            e.printStackTrace();
                            new BaseException("查询WFS保证金数据异常,请联系管理员");
                        }
                    }else{
                        depositCalculation.setOldAmount(depositCalculation.getCurrentAmount());
                        depositCalculationService.updateDepositCalculation(depositCalculation);
                    }
                }
            }
        }
        annualReviewy.setUpdateTime(DateUtils.getNowDate());
        annualReviewyMapper.updateAnnualReviewy(annualReviewy);
        return "1";

    }
    public StringBuffer sendWfsSetUpLimit(List<LimitActiveProposal> limitActiveProposalList,String dealerName,String sector, String dealerCode, String oem,String instanceId ){
        StringBuffer resp = new StringBuffer();
        WFSLimitSetup wfsLimitSetup = new WFSLimitSetup();
        wfsLimitSetup.setDealerName(dealerName);
        wfsLimitSetup.setInstanceId(instanceId);
        wfsLimitSetup.setSector(sector);
        List<LimitActiveProposal> limitActiveProposalListNew = new ArrayList<LimitActiveProposal>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        boolean flag =false;
        for (LimitActiveProposal limitActiveProposal : limitActiveProposalList) {
            //判断是否有Temp
            if((limitActiveProposal.getLimitType().toUpperCase()).equals("TEMP")){
                flag = true;

            }
        }
        if(flag){
            //重新组装
            Long  sum = 0l;
            for (LimitActiveProposal limitActiveProposal : limitActiveProposalList) {
                if((limitActiveProposal.getLimitType().toUpperCase()).equals("TEMP") || (limitActiveProposal.getLimitType().toUpperCase()).equals("NORMAL")){
                    try {
                        long l = new DecimalFormat().parse(limitActiveProposal.getProposalActiveLimit()).longValue();
                        sum =  l +sum;
                    } catch (ParseException e) {
                        throw new RuntimeException("金额转换异常");
                    }

                }
            }
            for (LimitActiveProposal limitActiveProposal : limitActiveProposalList) {
                if((limitActiveProposal.getLimitType().toUpperCase()).equals("TEMP")){
                    limitActiveProposal.setProposalActiveLimit(sum.toString());
                    limitActiveProposal.setLimitType("NEW");
                    limitActiveProposalListNew.add(limitActiveProposal);

                }else if(!(limitActiveProposal.getLimitType().toUpperCase()).equals("NORMAL")){
                    limitActiveProposalListNew.add(limitActiveProposal);
                }
            }

        }else{
            for (LimitActiveProposal limitActiveProposal : limitActiveProposalList) {
                if((limitActiveProposal.getLimitType().toUpperCase()).equals("NORMAL")){
                    limitActiveProposal.setLimitType("NEW");
                }
                limitActiveProposalListNew.add(limitActiveProposal);
            }
        }
        List<Object> ObjList = new ArrayList<Object>();
        HashMap<String, Object> map = new HashMap<>();
        for (LimitActiveProposal limitActiveProposal : limitActiveProposalListNew) {
            String end = sdf.format(limitActiveProposal.getProposedEnd());
            HashMap<String, Object> CreditLimit = new HashMap<>();
            HashMap<String, Object> creditDetailsMap = new HashMap<>();
            List<Object> creditDetailsList = new ArrayList<Object>();
            CreditLimit.put("DealerCode",dealerCode);
            CreditLimit.put("DistributorCode",oem);
            CreditLimit.put("ExpiryDate",end);
            CreditLimit.put("CreditType","Temporary");
            creditDetailsMap.put("Sector",sector);
            creditDetailsMap.put("LimitType",limitActiveProposal.getLimitType());
            try {
                long l = new DecimalFormat().parse(limitActiveProposal.getProposalActiveLimit()).longValue();
                creditDetailsMap.put("CreditLimit",l);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            creditDetailsList.add(creditDetailsMap);
            CreditLimit.put("CreditDetails",creditDetailsList);
            ObjList.add(CreditLimit);
        }
        map.put("CreditLimit",ObjList);
        JSONObject jsonObject = new JSONObject(map);
        log.info("WFS外部接口请求参数=[{}]", jsonObject);
        wfsLimitSetup.setReq(jsonObject.toJSONString());
        wfsLimitSetup.setCreateTime(new Date());
        wfsLimitSetup.setCreateBy(SecurityUtils.getUsername());
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(wfsUrl2 + "CreditLimit");
        httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
        StringEntity entity = new StringEntity(jsonObject.toString(), "utf-8");
        entity.setContentType("application/json;charset=UTF-8");
        entity.setContentEncoding("UTF-8");
        httpPost.setEntity(entity);
        httpPost.setHeader("Accept", "application/json, text/plain, */*");
        httpPost.setHeader("Accept-Encoding", "gzip, deflate");
        httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6");
        httpPost.setHeader("Connection", "keep-alive");
        httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36 Edg/93.0.961.38");
        try {
            HttpResponse response = httpClient.execute(httpPost);
            String responseStr = EntityUtils.toString(response.getEntity());
            wfsLimitSetup.setResp(responseStr);
            wfsLimitSetup.setUpdateTime(new Date());
            log.info("WFS外部接口数据返回结果=[{}]", responseStr);
            JSONArray jsonArray = new JSONArray(Collections.singletonList(responseStr));
            for (Object o : jsonArray) {
                Map<String, Object> respMap = JSON.parseObject((String) o,Map.class);
                Object creditLimit = respMap.get("CreditLimit");
                JSONArray CreditLimitList = new JSONArray(Collections.singletonList(creditLimit));
                if(CreditLimitList !=null && CreditLimitList.size()>0){
                    for (Object o1 : CreditLimitList) {
                        System.out.println(o1);
                        List<Map<String, Object>> CreditLimitMap = (List<Map<String, Object>>) o1;
                        for (Map<String, Object> stringObjectMap : CreditLimitMap) {
                            System.out.println(stringObjectMap);
                            List<Map<String, Object>> CreditDetails = (List<Map<String, Object>>) stringObjectMap.get("CreditDetails");
                            for (Map<String, Object> creditDetail : CreditDetails) {
                                Object Sector = creditDetail.get("Sector");
                                Object LimitType = creditDetail.get("LimitType");
                                Object Limit = creditDetail.get("CreditLimit");
                                String Code = (String) creditDetail.get("Code");
                                Object Message = creditDetail.get("Message");
                                System.out.println(creditDetail);
                                if(!Code.equals("000")){
                                    resp.append("额度类型 "+LimitType+"激活失败:"+Message).append("; ");
                                }
                            }
                        }
                    }
                }else{
                    resp.append("WFS外部接口无返回结果");
                }

            }
        }catch (Exception e){
            e.printStackTrace();
            return  resp.append("系统异常");
        }finally {
            limitActiveProposalMapper.insertWFSLimitSetup(wfsLimitSetup);
        }
        return  resp;
    }

    public Map<String, Object> getLimitActivationProposal4(DepositDecreaseDTO depositDecreaseDTO){

        DepositCalculation depositCalculationTemp = new DepositCalculation();
        depositCalculationTemp.setInstanceId(depositDecreaseDTO.getInstanceId());
        List<DepositCalculation> depositCalculationList = depositCalculationService.selectDepositCalculationList(depositCalculationTemp);
        String dealerCode = depositCalculationList.get(0).getDealerCode();
        List<String[]> strList = new ArrayList<String[]>();
        String[] str = new String[1];
        str[0] = dealerCode;
        strList.add(str);

        JSONObject jsonObject = new JSONObject();
        Map<String, Object> result = new HashMap<>();
        List<LimitActiveProposal> limitActiveProposals = new ArrayList<>();
        List<DepositCalculation> depositCalculations = new ArrayList<>();
//        String[] dealerCodes = depositDecreaseDTO.getDealerCodeArr().get(0);
        //String dealerCode = dealerCodes[0];
        //String dealerCode = "K55105";
        DealerInformation dealerInformation = new DealerInformation();
        dealerInformation.setDealerCode(dealerCode);
        List<DealerInformation> dealerInformations = dealerInformationService.selectDealerInformationList(dealerInformation);
        if (dealerInformations != null && dealerInformations.size() > 0) {
            dealerInformation = dealerInformations.get(0);
        }
        jsonObject.put("DealerCode", strList);
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(wfsUrl + "CreditInfo");
        HttpPost httpPost2 = new HttpPost(wfsUrl + "SuspenseInfo");
        httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
        httpPost2.addHeader("Content-Type", "application/json;charset=UTF-8");
        StringEntity entity = new StringEntity(jsonObject.toString(), "utf-8");
        entity.setContentType("application/json;charset=UTF-8");
        entity.setContentEncoding("UTF-8");
        httpPost.setEntity(entity);
        httpPost.setHeader("Accept", "application/json, text/plain, */*");
        httpPost.setHeader("Accept-Encoding", "gzip, deflate");
        httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6");
        httpPost.setHeader("Connection", "keep-alive");
        httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36 Edg/93.0.961.38");
        httpPost2.setEntity(entity);
        httpPost2.setHeader("Accept", "application/json, text/plain, */*");
        httpPost2.setHeader("Accept-Encoding", "gzip, deflate");
        httpPost2.setHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6");
        httpPost2.setHeader("Connection", "keep-alive");
        httpPost2.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36 Edg/93.0.961.38");
        Map<String, Object> objectList = new HashMap<>();
        Map<String, Object> objectList2 = new HashMap<>();
        try {
            Map<String, Object> stringObjectHashMap = new HashMap<>();
            stringObjectHashMap.put("Deposit",0);
            stringObjectHashMap.put("CBDeposit",0);
            stringObjectHashMap.put("PartDeposit",0);
            stringObjectHashMap.put("UsedDeposit",0);
            HttpResponse response = httpClient.execute(httpPost);
            String responseStr = EntityUtils.toString(response.getEntity());
            HttpResponse response2 = httpClient.execute(httpPost2);
            String responseStr2 = EntityUtils.toString(response2.getEntity());
            log.info("WFS外部接口数据返回结果=[{}]", responseStr);
            log.info("WFS外部接口数据返回结果2=[{}]", responseStr2);
            objectList = JSONObject.parseObject(responseStr, Map.class);
            objectList2 = JSONObject.parseObject(responseStr2, Map.class);
            if (Integer.valueOf(String.valueOf(objectList.get("Code"))) == 200) {
                Map data = (Map) JSONObject.parseArray(JSONObject.toJSONString(JSONObject.parseObject(JSONObject.toJSONString(JSONObject.parseArray(JSONObject.toJSONString(JSONObject.parseArray(JSONObject.toJSONString(objectList.get("Data"))).get(0))).get(0)), Map.class).get("CreditInfo"))).get(0);
                List creditDet = (List) data.get("CreditDet");
                try{
                    stringObjectHashMap = JSONObject.parseObject(String.valueOf(JSONObject.parseObject(String.valueOf(JSONObject.parseArray(JSONObject.toJSONString(JSONObject.parseArray(JSONObject.toJSONString(objectList2.get("Data"))).get(0))).get(0))).get("SuspenseInfo")), Map.class);
                }catch (NullPointerException e){

                }
                stringObjectHashMap.put("Deposit",stringObjectHashMap.get("Deposit") != null ? stringObjectHashMap.get("Deposit") : 0);
                stringObjectHashMap.put("CBDeposit",stringObjectHashMap.get("CBDeposit") != null ? stringObjectHashMap.get("CBDeposit") : 0);
                stringObjectHashMap.put("PartDeposit",stringObjectHashMap.get("PartDeposit") != null ? stringObjectHashMap.get("PartDeposit") : 0);
                stringObjectHashMap.put("UsedDeposit",stringObjectHashMap.get("UsedDeposit") != null ? stringObjectHashMap.get("UsedDeposit") : 0);
                List<Map<String, Object>> creditDets = creditDet;
                //是否存在NORMAL

                //NORMAL 数据
                BigDecimal zero = new BigDecimal(0);
                Map<String, Object> normalData = null;
                Boolean flag = true;
                for (int i = 0; i < creditDets.size(); i++) {
                    Map<String, Object> objectMap = creditDets.get(i);
                    if(objectMap.get("LimitType").toString().equalsIgnoreCase("NORMAL")){
                        normalData = creditDets.get(i);
                        break;
                    }
                }

                for (int i = 0; i < creditDets.size(); i++) {
                    Map<String, Object> objectMap = creditDets.get(i);
                    LimitActiveProposal limitActiveProposal = new LimitActiveProposal();
                    limitActiveProposal.setDealerName(dealerInformation.getDealerName());
                    limitActiveProposal.setDealerCode(dealerCode);
                    limitActiveProposal.setSector(dealerInformation.getMake());

                    limitActiveProposal.setLimitType(String.valueOf(objectMap.get("LimitType")));
                    limitActiveProposal.setCurrentCreditLimit(Long.valueOf(String.valueOf(objectMap.get("CreditLimit"))));

                    //激活额度
                    limitActiveProposal.setCurrentActiveLimit(String.valueOf(objectMap.get("ActiveLimit")));
                    if(objectMap.get("LimitType").toString().equalsIgnoreCase("TEMP")){
                        limitActiveProposal.setCurrentActiveLimit("");
                    }


                    //设置保证金比例
                    if(objectMap.get("LimitType").toString().equalsIgnoreCase("CB")){
                        limitActiveProposal.setApprovedCashDeposit(String.valueOf(objectMap.get("SecurityRatio")));
                    }else if(objectMap.get("LimitType").toString().equalsIgnoreCase("TEMP") || objectMap.get("LimitType").toString().equalsIgnoreCase("MGR") ){
                        //limitActiveProposal.setApprovedCashDeposit("");
                    }else if(ObjectUtil.isNotEmpty(normalData) && (objectMap.get("LimitType").toString().equalsIgnoreCase("NORMAL") || objectMap.get("LimitType").toString().equalsIgnoreCase("DEMO")  || objectMap.get("LimitType").toString().equalsIgnoreCase("USED"))){
                        limitActiveProposal.setApprovedCashDeposit(String.valueOf(normalData.get("SecurityRatio")));
                    }


                    limitActiveProposal.setOs(String.valueOf(objectMap.get("ActiveOS")));
                    if(!StringUtils.isEmpty(String.valueOf(objectMap.get("ActiveExpireDate")))){
                        String activeExpireDate = String.valueOf(objectMap.get("ActiveExpireDate"));
                        String replace = activeExpireDate.replace("/", "-");
                        limitActiveProposal.setCurrentActiveLimitExpiryDate(replace);
                    }else{
                        limitActiveProposal.setCurrentActiveLimitExpiryDate(null);
                    }

                    if (objectMap.get("LimitType").equals("NORMAL") || objectMap.get("LimitType").equals("DEMO")) {
                        limitActiveProposal.setProposalCashDeposit(String.valueOf(stringObjectHashMap.get("Deposit")));

                    } else if (objectMap.get("LimitType").equals("CB")) {
                        limitActiveProposal.setProposalCashDeposit(String.valueOf(stringObjectHashMap.get("CBDeposit")));
                    } else if (objectMap.get("LimitType").equals("PART")){
                        limitActiveProposal.setProposalCashDeposit(String.valueOf(stringObjectHashMap.get("PartDeposit")));
                    }else if (objectMap.get("LimitType").equals("USED")){
                        limitActiveProposal.setProposalCashDeposit(String.valueOf(stringObjectHashMap.get("UsedDeposit")));
                    }
                    if (StringUtils.isNotEmpty(limitActiveProposal.getApprovedCashDeposit())) {
                        if(StringUtils.isNotEmpty(limitActiveProposal.getApprovedCashDeposit()) && StringUtils.isNotEmpty(limitActiveProposal.getProposalCashDeposit())){
                            //Double aDouble = Double.valueOf(limitActiveProposal.getApprovedCashDeposit().replace("%", ""));
                            String replace = limitActiveProposal.getApprovedCashDeposit().replace("%", "");
                            BigDecimal bigDecimal2 = new BigDecimal(limitActiveProposal.getProposalCashDeposit());
                            BigDecimal bigDecimal3 = new BigDecimal(replace).setScale(4, BigDecimal.ROUND_CEILING);
                            BigDecimal bigDecimal4 = bigDecimal2.divide(bigDecimal3,4,BigDecimal.ROUND_HALF_UP);
                            BigDecimal bigDecimal5 = bigDecimal4.multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP);
                            //BigDecimal bigDecimal = new BigDecimal(limitActiveProposal.getProposalCashDeposit()).divide(new BigDecimal(aDouble)).setScale(2, BigDecimal.ROUND_HALF_UP);
                            //BigDecimal bigDecimal1 = bigDecimal.divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP);


                            limitActiveProposal.setLimitCoveredDeposit(bigDecimal5.toString());
                        }
                    } else {
                        limitActiveProposal.setLimitCoveredDeposit("");
                    }
                    limitActiveProposal.setProposedStart(new Date());
                    if(objectMap.get("LimitType").toString().equals("TEMP")){
                        //手动输入
                        limitActiveProposal.setProposedEnd(null);
                        limitActiveProposal.setProposedExpiredDate(null);
                    }else if ((objectMap.get("LimitType").toString().equals("DEMO") ||  objectMap.get("LimitType").toString().equals("CB"))&& ObjectUtil.isNotEmpty(normalData)){
                        if(StringUtils.isNotEmpty(normalData) &&  normalData.get("ExpiryDate")!=null) {
                            limitActiveProposal.setProposedEnd(new Date(String.valueOf(normalData.get("ExpiryDate"))));
                            limitActiveProposal.setProposedExpiredDate(new Date(String.valueOf(normalData.get("ExpiryDate"))));
                        }
                    }else if (objectMap.get("LimitType").toString().equals("PART") && ObjectUtil.isNotEmpty(normalData)){
                        if(StringUtils.isNotEmpty(normalData) &&  normalData.get("ExpiryDate")!=null) {
                            limitActiveProposal.setProposedEnd(new Date(String.valueOf(normalData.get("ExpiryDate"))));
                            limitActiveProposal.setProposedExpiredDate(new Date(String.valueOf(normalData.get("ExpiryDate"))));
                        }
                    }else if (StringUtils.isNotEmpty(String.valueOf(objectMap.get("ExpiryDate")))){
                        limitActiveProposal.setProposedEnd(new Date(String.valueOf(objectMap.get("ExpiryDate"))));
                        limitActiveProposal.setProposedExpiredDate(new Date(String.valueOf(objectMap.get("ExpiryDate"))));
                    }
                    DealercodeContractFiling dealercodeContractFiling = new DealercodeContractFiling();
                    dealercodeContractFiling.setDealerNameCN(dealerInformation.getDealerName());
                    dealercodeContractFiling.setSector(dealerInformation.getMake());
                    dealercodeContractFiling.setLimitType(String.valueOf(objectMap.get("LimitType")));
                    List<DealercodeContractFiling> dealercodeContractFilings = dealercodeContractFilingMapper.selectDealercodeContractFilingListRecentlyEffectiveDate(dealercodeContractFiling);
                    if(StringUtils.isNotEmpty(dealercodeContractFilings)){
                        Date parse = null;
                        if(StringUtils.isNotEmpty(dealercodeContractFilings.get(0).getFacilityAmount())) {
                            limitActiveProposal.setContractFacilityAmount(dealercodeContractFilings.get(0).getFacilityAmount());
                        }
                        if(StringUtils.isNotEmpty(dealercodeContractFilings.get(0).getExpiredDate())) {
                            try {
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                                parse = sdf.parse(dealercodeContractFilings.get(0).getExpiredDate());
                            } catch (Exception e) {
                                e.printStackTrace();
                                new BaseException("日期转化异常");
                            }
                            limitActiveProposal.setContractExpireDate(parse);
                        }
                        if(StringUtils.isNotEmpty(dealercodeContractFilings.get(0).getDeposit())) {
                            limitActiveProposal.setContractDepositRatio(dealercodeContractFilings.get(0).getDeposit());
                        }
                        if(StringUtils.isNotEmpty(dealercodeContractFilings.get(0).getContractLocation())){
                            limitActiveProposal.setContractHyperlink(dealercodeContractFilings.get(0).getContractLocation());
                        }
                    }
                    DepositCalculation depositCalculation = new DepositCalculation();
                    depositCalculation.setDealerName(limitActiveProposal.getDealerName());
                    depositCalculation.setDealerCode(limitActiveProposal.getDealerCode());
                    depositCalculation.setSector(limitActiveProposal.getSector());
                    depositCalculation.setLimitType(limitActiveProposal.getLimitType());
                    depositCalculation.setCurrentAmount(String.valueOf(limitActiveProposal.getProposalCashDeposit()));
                    // depositCalculation.setProposedAmount(String.valueOf(Long.valueOf(limitActiveProposal.getProposalActiveLimit()) * Double.valueOf(limitActiveProposal.getApprovedCashDeposit().replace("%", ""))));
                    // depositCalculation.setGap(String.valueOf(Double.valueOf(depositCalculation.getProposedAmount()) - Double.valueOf(depositCalculation.getCurrentAmount())));
                    depositCalculations.add(depositCalculation);
                    limitActiveProposals.add(limitActiveProposal);
                }
            }
            log.info("WFS外部接口数据返回JSON结果=[{}]", JSON.toJSONString(responseStr));

        } catch (IOException e) {
            e.printStackTrace();
        }

        List<DepositCalculation> calculations = new ArrayList<>();

        for (DepositCalculation depositCalculation : depositCalculations) {
            if(depositCalculation.getLimitType().equals("NORMAL") || depositCalculation.getLimitType().equals("DEMO") || depositCalculation.getLimitType().equals("TEMP") ){
                calculations.add(depositCalculation);
            }
        }

        if(calculations.size() >= 2){
            Iterator<DepositCalculation> iterator = depositCalculations.iterator();

            while(iterator.hasNext()) {
                DepositCalculation next = iterator.next();

                if (next.getLimitType().equals("NORMAL") || next.getLimitType().equals("DEMO") || next.getLimitType().equals("TEMP")) {
                    iterator.remove();
                }
            }

            DepositCalculation depositCalculation = calculations.get(0);
            depositCalculation.setLimitType("NORMAL/DEMO/TEMP");
            depositCalculations.add(depositCalculation);

        }
        List<HLimitSetupResult> hLimitSetupResults = new ArrayList<>();
        for (LimitActiveProposal limitActiveProposal : limitActiveProposals) {
            limitActiveProposal.setSort(typeSort(limitActiveProposal.getLimitType()));
            HLimitSetupResult hLimitSetupResult = new HLimitSetupResult();
            hLimitSetupResult.setDealername(limitActiveProposal.getDealerName());
            hLimitSetupResult.setSector(limitActiveProposal.getSector());
            hLimitSetupResult.setLimittype(limitActiveProposal.getLimitType());
            hLimitSetupResult.setCurrentactivelimit(limitActiveProposal.getCurrentActiveLimit());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

            try {
                if(limitActiveProposal.getCurrentActiveLimitExpiryDate()!=null){
                    Date parse = sdf.parse(limitActiveProposal.getCurrentActiveLimitExpiryDate());
                    hLimitSetupResult.setCurrentactivelimitexpirydate(parse);
                }

            }catch (Exception e){
                e.printStackTrace();
            }
            hLimitSetupResult.setOs(limitActiveProposal.getOs());
            hLimitSetupResult.setSort(typeSort(limitActiveProposal.getLimitType()));
            hLimitSetupResults.add(hLimitSetupResult);
        }
        hLimitSetupResults.sort(Comparator.comparingInt(HLimitSetupResult::getSort));
        result.put("limitSetupResult",hLimitSetupResults);

        //先删后插
        HLimitSetupResult hLimitSetupResult = new HLimitSetupResult();
        hLimitSetupResult.setInstanceid(depositDecreaseDTO.getInstanceId());
        List<HLimitSetupResult> hLimitSetupResultsUpdate = limitSetupResultService.selectHLimitSetupResultList(hLimitSetupResult);
        for (HLimitSetupResult limitSetupResult : hLimitSetupResultsUpdate) {
            limitSetupResultService.deleteHLimitSetupResultById(limitSetupResult.getId());
        }
        for (HLimitSetupResult limitSetupResult : hLimitSetupResults) {
            limitSetupResult.setInstanceid(depositDecreaseDTO.getInstanceId());
            limitSetupResultService.insertHLimitSetupResult(limitSetupResult);
            System.out.println("更新setupResult");
        }

        return result;
    }

    public AjaxResult getDeposit(@RequestBody DepositDecreaseDTO depositDecreaseDTO) throws IOException {
        JSONObject jsonObject = new JSONObject();
        List<String[]> dealerCodeArr = depositDecreaseDTO.getDealerCodeArr();
        jsonObject.put("DealerCode", depositDecreaseDTO.getDealerCodeArr());
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
//        HttpPost httpPost = new HttpPost("http://10.226.186.86:8081/CreditLoanSuspenseAPIUAT7/CreditInfo");
        HttpPost httpPost = new HttpPost(wfsUrl + "SuspenseInfo");
        httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
        StringEntity entity = new StringEntity(jsonObject.toString(), "utf-8");
        entity.setContentType("application/json;charset=UTF-8");
        entity.setContentEncoding("UTF-8");
        httpPost.setEntity(entity);
        httpPost.setHeader("Accept", "application/json, text/plain, */*");
        httpPost.setHeader("Accept-Encoding", "gzip, deflate");
        httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6");
        httpPost.setHeader("Connection", "keep-alive");
        httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36 Edg/93.0.961.38");
        Map<String, Object> objectList = new HashMap<>();
        List<Map<String, String>> maps = new ArrayList<>();
        ArrayList<String> stringNew = new ArrayList<>();
        ArrayList<String> stringOld = new ArrayList<>();
        try {
            HttpResponse response = httpClient.execute(httpPost);
            String responseStr = EntityUtils.toString(response.getEntity());
            log.info("WFS外部接口数据返回结果=[{}]", responseStr);
            objectList = JSONObject.parseObject(responseStr, Map.class);
            log.info("WFS外部接口数据返回JSON结果=[{}]", JSON.toJSONString(responseStr));
            try{
              /*  stringObjectHashMap = JSONObject.parseObject(String.valueOf(JSONObject.parseObject(String.valueOf(JSONObject.parseArray(JSONObject.toJSONString(JSONObject.parseArray(JSONObject.toJSONString(objectList.get("Data"))).get(0))).get(0)))), Map.class);
                System.out.println(stringObjectHashMap);*/
                Object data = objectList.get("Data");
                JSONArray data1 = JSONObject.parseArray(JSONObject.toJSONString(objectList.get("Data")));
                if(data1!=null && data1.size()>0){
                    for (Object o : data1) {
                        System.out.println(o);
                        JSONArray data2 = JSONObject.parseArray(JSONObject.toJSONString(o));
                        if(data2!=null && data2.size()>0){
                            for (Object o1 : data2) {
                                Map<String, Object>  stringObjectHashMap =  JSONObject.parseObject(JSONObject.toJSONString(o1),Map.class);
                                if(stringObjectHashMap != null && stringObjectHashMap.get("DealerCode")!=null && stringObjectHashMap.get("SuspenseInfo")!=null ){
                                    Map<String, Object>  suspenseInfo = JSONObject.parseObject(JSONObject.toJSONString(stringObjectHashMap.get("SuspenseInfo")), Map.class);
                                    if(suspenseInfo!=null && suspenseInfo.get("Deposit")!=null){
                                        HashMap<String, String> stringStringHashMap = new HashMap<>();
                                        stringStringHashMap.put("DealerCode",stringObjectHashMap.get("DealerCode").toString());
                                        stringNew.add(stringObjectHashMap.get("DealerCode").toString());
                                        stringStringHashMap.put("Deposit",suspenseInfo.get("Deposit").toString());
                                        if(suspenseInfo.get("CBDeposit")!=null){
                                            stringStringHashMap.put("CBDeposit",suspenseInfo.get("CBDeposit").toString());
                                        }
                                        if(suspenseInfo.get("PartDeposit")!=null){
                                            stringStringHashMap.put("PartDeposit",suspenseInfo.get("PartDeposit").toString());
                                        }
                                        if(suspenseInfo.get("UsedDeposit")!=null){
                                            stringStringHashMap.put("UsedDeposit",suspenseInfo.get("UsedDeposit").toString());
                                        }
                                        stringStringHashMap.put("TEMPDeposit","-");
                                        maps.add(stringStringHashMap);
                                    }
                                }
                            }
                        }
                    }
                }
            }catch (NullPointerException e){
                e.printStackTrace();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        List<String[]> dealerCodeArr1 = depositDecreaseDTO.getDealerCodeArr();
        for (String[] strings : dealerCodeArr1) {
            if(strings!=null && strings.length>0){
                for (String string : strings) {
                    stringOld.add(string);
                }
            }
        }
        if(stringOld.size()>stringNew.size()){
            stringOld.removeAll(stringNew);
            if(stringOld.size()>0){
                for (String s : stringOld) {
                    HashMap<String, String> stringStringHashMap = new HashMap<>();
                    stringStringHashMap.put("DealerCode",s);
                    stringStringHashMap.put("Deposit","0");
                    stringStringHashMap.put("CBDeposit","0");
                    stringStringHashMap.put("TEMPDeposit","0");
                    stringStringHashMap.put("PartDeposit","0");
                    stringStringHashMap.put("UsedDeposit","0");
                    maps.add(stringStringHashMap);
                }
            }
        }
        return AjaxResult.success(maps);
    }
}
